I have a form with an option element on top and an email field.
<form class="form-versenden" action="mainVersendet.php" method="post" name="send">
<div class="form-group">
<h4>Bitte tragen Sie die folgenden Daten ein</h4>
<div class="form-group">
<label for="versandart">Versandart</label>
<select class="form-control" id="versandart" name="versandart" autofocus>
<option value="both">E-Mail und Druck</option>
<option value="onlyEmail">Nur E-Mail</option>
<option value="onlyPrint">Nur Druck</option>
</select>
</div>
<div class="form-group">
<label for="email">E-Mail</label>
<input type="email" class="form-control" id="email" placeholder="email" name="email">
</div>
<button class="btn" type="submit">Versenden</button>
</div>
</form>
Depending on what the user chooses, I have to check if an email address is entered in the case 'both' and 'onlyEmail'. Because email is not required in all 3 cases I can't use the required element of HTML for the email field. So I tried to test it on the submit event like this:
document.querySelector('form[name="send"]').addEventListener("submit", validateFields);
function validateFields(){
var versandart = document.getElementById("versandart");
var email = document.getElementById("email");
if (versandart.value == 'both' || versandart.value == 'onlyEmail'){
if(email.value == ''){
email.setCustomValidity('EMail muss eingegeben werden');
return false;
}else if(CHECK HERE if Mail is not correct){
email.setCustomValidity('EMail format is not correct');
return false;
}else{
//in this case email is not empthy and is correct
return true;
}
}
}
But this is not working because I overwrite the standard HTML check for a valid email address. So I have to check it again at the point 'CHECK HERE if Mail is not correct'.
How can I do that and is that the right way? Or should I add an onchangelistener to the versandart field and add the required tag to the email field if the selected value is fitting into the first two cases?
In your else if, use the isEmail() function like this:
else if(email.value.isEmail()) {
return true;
// Now the form will get submitted to the PHP script.
}
string.isEmail() returns true if the entered pattern matches an email address, otherwise false.
Please don't forget to do server side form validation, too, though. If a cracker switches JavaScript off, they may cause mayhem in your system if you only have JavaScript validation -- especially as you apparently can't use required HTML attribute for your email input.
Related
I'm making two forms with html and javascript, one for "log in" and one for "register". Im using javascript to check that the inputs on the forms are valid. Im running into an issue where the "email" field on the "log in" form is being validated properly, but the "email" field on my "register" form is not, although they are using nearly identical event listeners to validate the inputs.
this is a condensed version of the code that I am using to do this
<html>
<form class="forms" id="login-form" onsubmit="return false" novalidate>
<h1>Log In</h1>
<div class="form-div">
<label for="email">Your Email:</label>
<input type="email" id="email" name="email" required>
<span class="error"></span>
</div>
<button class="wide-buttons" type="submit">Log In</button>
<p onclick="toggleForms()">Need an account? Click here to sign up!</p>
</form>
<form class="forms" id="register-form" onsubmit="return false" novalidate>
<h1>Register</h1>
<div class="form-div">
<label for="email">Your Email:</label>
<input type="email" id="register-email" name="register-email" required>
<span class="error"></span>
</div>
<button class="wide-buttons" type="submit" onclick="validateRegister()">Sign Up</button>
<p onclick="toggleForms()">Already have an account? Click here to log in!</p>
</form>
<script>
const loginForm = document.getElementById("login-form");
const emailError = document.querySelector("#email + span.error");
const registerForm = document.getElementById('register-form');
const regEmailError = document.querySelector("#register-email + span.error");
loginForm.addEventListener("submit", (event) => {
if (!email.validity.valid) {
emailError.textContent = "You must enter a valid email address";
}
});
registerForm.addEventListener("submit", (event) => {
if (!email.validity.valid) {
regEmailError.textContent = "You must enter a valid email address";
}
});
</script>
Im using event listeners for a "submit" event on each form and the one for "loginForm" Is working the way that I intend it to, but the one for "registerForm" is showing my error message when the email is a valid email or anything else is put into the email field. Im stumped by this considering the listeners are practically identical. I don't need to actually submit the form to anything, I'm just trying to learn how some basic form validation works. This code is a snippet of everything else that I have written, but my passwords, checkboxes, etc. are working fine for me. I just need to know how to get the "registerForm" event listener to work the same way that the "loginForm" one is.
edit: Im aware of the onclick="validateRegister()" on the register form- I have removed this in my code and I am still having the issue.
Any help, constructive criticism, or funny jokes are appreciated.
thanks.
It looks like you are trying to check the validity of the email input element on both forms, but you should be checking the validity of the register-email input element on the registerForm event listener.
Change:
if (!email.validity.valid) {
regEmailError.textContent = "You must enter a valid email address";
}
To:
const registerEmail = document.getElementById('register-email');
if (!registerEmail.validity.valid) {
regEmailError.textContent = "You must enter a valid email address";
}
and it should be ok
Edit1: Ofc you can declare registerEmail above event listener
I have this code to validate inputs:
<script>
function validate()
{
var firstName = document.form.fullname.value;
var lastName = document.form.fullname.value;
var email = document.form.email.value;
var password = document.form.password.value;
var conpassword = document.form.conpassword.value;
if (firstName == null || firstName == "")
{
alert("Firstname can't be blank");
return false;
} else if (lastName == null || lastName == "")
{
alert("Lastname can't be blank");
return false;
} else if (email == null || email == "")
{
alert("Email can't be blank");
return false;
} else if (password.length < 6)
{
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
And this is my form:
<form name="form" action="<%=request.getContextPath()%>/register" method="post">
<div class="container">
<div class="left">
<div class="header">
<h2 class="animation a1">Register now</h2>
<h4 class="animation a2">Enter information in field and create account!</h4>
</div>
<div class="form">
<input type="text" name="firstName" class="form-field animation a3" placeholder="Name...">
<input type="text" name="lastName" class="form-field animation a3" placeholder="Last name...">
<input type="email" name="email" class="form-field animation a3" placeholder="Email adress...">
<input type="password" name="password" class="form-field animation a4" placeholder="Password">
<button class="animation a6" value="Submit" type="submit">REGISTER</button>
</div>
</div>
<div class="right"></div>
</div>
</form>
How to implement that function to my form? Because now when I click submit, in my database an empty user is added. I want to add that it throws out an error in each field if it is not validly filled in
You can get the validate function to execute by adding an 'onsubmit' to your form html tag ( see here w3 Schools for executing a function on submit: onsubmit in forms)
As for the errors, when executing the code, the function cannot read a property 'value' of undefined. So what is happening is that you are telling the validate function to get parts out of the form out that it cannot find (fullname and conpassword are not defined).
Take a look at your form's name tags for fields and then reference those names in the validate function. So when declaring firstName instead of document.form.fullname.value try document.form.firstName.value referring in the form. Do this for first and last name using their names in the form, and also get rid of (or comment out) the conpassword variable.
This validation could be done without javascript function. Use the "required" tag for the inputs which are mandatory.
For example :
<input type="text" name="firstName" class="form-field animation a3" placeholder="Name..." required>
In case of password you may use the pattern attribute.
If you need to use javascript in particular, then go for onclick in the button tag.
<button class="animation a6" onclick="validate()">REGISTER</button>
and include the form submit in the javascript function -
document.form.submit();
I have a form that is supposed to register a user and I have two inputs for passwords that are supposed to be the same. I use html for the form and javascript to check if both inputs are matching. The code I'm using doesn't work though because even if the passwords are different, the user data is still sent to my console when the form shouldn't be able to submit in the first place. These are portions of my html file.
<form id="registration-info" method="POST" action="/registration" onsubmit="return validatePassword();">
....
<div class="mb-3">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" id="password" required>
<div class="invalid-feedback">
Please enter a password.
</div>
</div>
<div class="mb-3">
<label for="repeat_password">Repeat Password</label>
<input type="password" class="form-control" name="repeat_password" id="repeat_password"required>
<script language='javascript' type='text/javascript'>
var password = document.getElementById("password")
, repeat_password = document.getElementById("repeat_password");
function validatePassword(){
if(password.value != repeat_password.value) {
document.repeat_password.setCustomValidity("Passwords Don't Match");
} else {
document.repeat_password.setCustomValidity('');
}
}
</script>
</div>
You have a few mistakes there you'll need to fix up.
Use a JavaScript event listener and remove document..
form = document.getElementById("registration-info");
form.onclick = function() {
var password = document.getElementById("password");
var repeat_password = document.getElementById("repeat_password");
if(password.value != repeat_password.value) {
repeat_password.setCustomValidity("Passwords Don't Match");
} else {
document.repeat_password.setCustomValidity('');
}
}
You do not need to use document. when references variables you have set. Using a JavaScript event listener helps you write clean code, that separates UI and logic.
<div class="form-style-5">
<form action="send-sms.php" method="POST">
<fieldset>
<legend><span class="number">1</span> Your Information</legend>
<input type="text" name="field1" id="name" placeholder="Your Name *">
<input type="email" name="field2" id="contact"placeholder="Contact Information (Email, Phone Number, etc.) *">
<input type="location" name="field3" id="location" placeholder="Your Location (i.e. McNutt, Hodge Hall, exact address, etc.)*">
<input type="text" name="field4" id="misc" placeholder="Miscellaneous Information That May Be Important"></textarea>
<label for="job">Urgency:</label>
<select id="job" name="field5">
<optgroup label="Urgency level: just for us to prioritize properly">
<option value="Not Urgent">Low (ETA: Up to an hour)</option>
<option value="reading">Normal (ETA: Up to 45 mins)</option>
<option value="boxing">Critical (ETA: ASAP!)</option>
</optgroup>
</select>
</fieldset>
<fieldset>
<legend><span class="number">2</span>Task that needs completion</legend>
<input type="text" id="task" name="field6" placeholder="Let Us Know How We Can Help!*"></input>
</fieldset>
<input name="submit" type="submit" value="Submit" onClick="push();validateForm();"/>
</form>
</div>
I'm using simple JS validation function which gets called "onClick" my submit button. My error messages get displayed correctly if someone submits an empty form, however, once you press "OK" on that alert, the form still gets submitted. I have a similar validation system on a different form and it runs smoothly.... Any modifications to my code, even if it doesn't solve the overall problem, would be appreciated.
function validateForm() {
var errormessage = "";
if (document.getElementById('name').value == "") {
errormessage += "Please enter your name. \n";
document.getElementById('name').style.borderColor = "red";
}
if (document.getElementById('contact').value == "") {
errormessage += "Please enter your contact. \n";
document.getElementById('contact').style.borderColor = "red";
}
if (document.getElementById('location').value == "") {
errormessage += "Tell us where to come! \n";
document.getElementById('location').style.borderColor = "red";
}
if (document.getElementById('task').value == "") {
errormessage += "Tell us how we can help! \n";
document.getElementById('task').style.borderColor = "red";
}
if (errormessage != "") {
alert(errormessage);
return false;
}
return true;
};
In order to prevent the form submission, the event must be stopped. The click handler setup will bubble to submission because it does not provide a way to stop the event.
An easy way is returning false, as you have attempted in the shown function. However, that return value is not being used. Note that your inline event handler looks like this
onClick="push();validateForm();"
As the value from validateForm is never used, the event handler continues on after the call to validation. The fix is to use the return value
onClick="push();return validateForm();"
Which will now properly stop the event if validation fails.
I am using a subscribe news letter script by using MySQL and PHP. When the user enters the e-mail and clicks the button the e-mail is added to database.
The issue is that while clicking the button without entering an e-mail, the data base is updating with an empty record. How can I stop submitting the empty fields and force the user to enter an e-mail?
Here is my HTML:
<form id="myForm" action="update.php" method="post">
<input type="hidden" name="action" value="update" />
<input type="text" name="email" id="email" value="Enter your email here" onfocus="if (this.value == 'Enter your email here') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Enter your email here';}" onwebkitspeechchange="this.value = this.value.replace('Enter your email here','')"; style=" color:#999; font-size:1em;width:200px; font-style:italic; font-family:"Times New Roman", Times, serif;"/>
<input class="button" type="image" src="rss.png" />
</form>
Sounds to me like you need to do some form validation before you take the user input and insert it into your database. It's dangerous to do as you're doing.
Why not use one of the many plugins out there:
http://www.queness.com/post/10104/powerful-javascript-form-validation-plugins
This is a useful tutorial on using the jquery validation plugin: http://docs.jquery.com/Plugins/Validation
Ignore the styling in their example and focus on the core aspects. In your case, the most useful line is:
<input id="cemail" name="email" size="25" class="required email" />
Roughly, you would need to do something like..
var form = $('#mtForm');
$('input').change(function(){
if($((this).val() == ''){
form.unbind('submit').submit(function(){
return false;
});
}
else{
form.unbind('submit');
}
})
You should change the value attribute of your email field to a placeholder attribute. The onfocus, onwebkitspeechchange and onblur code can be removed from the email input tag.
You can use something like this to check for a blank field if that's the only type of validation you're after (below is written with jQuery).
$(function(){
$('#myForm').submit(function(e){
if ($('#email').val().trim() == "") {
// some sort of notification here
e.preventDefault();
return false;
}
});
});
Ideally, you would validate the form on the client side (javascript/JQuery) as well as the server side (php).
For clarity I will remove the inline code on your input box to get this:
<input type="text" name="email" id="email" value="Enter your email here" />
Note - You may use
placeholder='Enter your email here'
to get the prompt in your input box.
Client side validation using HTML5
Make a required field with email format validation:
<input type="email" name="email" id="email" value="Enter your email here" required="required"/>
Client side validation using javascript/JQuery - example.js
JQuery:
$('#email').bind('blur', function() {
if (!validateEmail($(this).val()) {
// Add errors to form or other logic such as disable submit
}
});
function validateEmail($email) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test($email);
}
}
Server side validation - update.php
// Require the email
if (empty($_POST['email'])) {
$error_message = 'You must enter an email!';
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$error_message = 'Invalid email format. Example: example#example.example';
} else { // If no errors, continue processing the form
// process the form, enter email
}
The HTML5 alone will prevent submission of the form, however only more recent browsers support HTML5.
Hope this is helpful!