I have created a form that validates using JQuery and JavaScript. The only problem is, would be that it validates one field at a time. So the user has to correct the first field first and then press submit again to see if the next field is valid.
What I would like to to do, is have the JQuery validate the whole form after pressing submit and show all the applicable error messages.
Here is My JS:
function validateUserName()
{
var u = document.forms["NewUser"]["user"].value
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "")
{
$("#ErrorUser").text("You Left the Username field Emptyyy");
return false;
}
else if (uLength < 4 || uLength > 11)
{
$("#ErrorUser").text("The Username must be between 4 and 11 characters");
return false;
}
else if (illegalChars.test(u))
{
$("#ErrorUser").text("The Username contains illegal charectors men!");
return false;
}
else
{
return true;
}
}
function validatePassword()
{
var p = document.forms["NewUser"]["pwd"].value
var cP = document.forms["NewUser"]["confirmPwd"].value
var pLength = p.length;
if (p == null || p == "")
{
$("#ErrorPassword1").text("You left the password field empty");
return false;
}
else if (pLength < 6 || pLength > 20)
{
$("#ErrorPassword1").text("Your password must be between 6 and 20 characters in length");
return false;
}
else if (p != cP)
{
$("#ErrorPassword1").text("Th passwords do not match!");
return false;
}
else
{
return true;
}
}
function validateEmail()
{
var e = document.forms["NewUser"]["email"].value
var eLength = e.length;
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (eLength == "" || eLength == null)
{
$("#ErrorEmail").text("You left the email field blank!");
return false;
}
else if (e.match(illegalChars))
{
$("#ErrorEmail").text("ILEGAL CHARECTORS DETECTED EXTERMINATE");
return false;
}
else
{
return true;
}
}
function validateFirstName()
{
var f = document.forms["NewUser"]["fName"].value;
var fLength = f.length;
var illegalChars = /\W/;
if (fLength > 20)
{
$("#ErrorFname").text("First Name has a max of 20 characters");
return false;
}
else if (illegalChars.test(f))
{
$("#ErrorFname").text("Numbers,letter and underscores in first name only");
return false;
}
else
{
return true;
}
}
function validateLastName()
{
var l = document.forms["NewUser"]["lName"].value;
var lLength = l.length;
var illegalChars = /\W/;
if (lLength > 100)
{
$("#ErrorLname").text("Last Name has a max of 100 characters");
return false;
}
else if (illegalChars.test(f))
{
$("#ErrorLname").text("Numbers,letter and underscores in last name only");
return false;
}
else
{
return true;
}
}
function validateForm()
{
valid = true;
//call username function
valid = valid && validateUserName();
//call password function
valid = valid && validatePassword();
//call email function
valid = valid && validateEmail();
//call first name function
valid = valid && validateFirstName();
//call first name function
valid = valid && validateLastName();
return valid;
}
And here is my submit form code:
$('#your-form').submit(validateForm);
Instead of returning true or false return a string containing the error and an empty string if no error was found.
Then validateForm could be something like
function validateForm()
{
error = "";
//call username function
error += "\n"+validateUserName();
//call password function
error += "\n"+validatePassword();
...
if(error === ""){
return true;
}
$("#ErrorLname").text(error);
return false;
}
Working Fiddle
var validate;
function validateUserName()
{
validate = true;
var u = document.forms["NewUser"]["user"].value
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "")
{
$("#ErrorUser").text("You Left the Username field Emptyyy");
validate = false;
}
else if (uLength <4 || uLength > 11)
{
$("#ErrorUser").text("The Username must be between 4 and 11 characters");
validate = false;
}
else if (illegalChars.test(u))
{
$("#ErrorUser").text("The Username contains illegal charectors men!");
validate = false;
}
}
function validatePassword()
{
var p = document.forms["NewUser"]["pwd"].value
var cP = document.forms["NewUser"]["confirmPwd"].value
var pLength = p.length;
if (p == null || p == "")
{
$("#ErrorPassword1").text("You left the password field empty");
validate = false;
}
else if (pLength < 6 || pLength > 20)
{
$("#ErrorPassword1").text("Your password must be between 6 and 20 characters in length");
validate = false;
}
else if (p != cP)
{
$("#ErrorPassword1").text("Th passwords do not match!");
validate = false;
}
}
function validateEmail()
{
var e = document.forms["NewUser"]["email"].value
var eLength = e.length;
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/ ;
var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
if (eLength == "" || eLength == null)
{
$("#ErrorEmail").text("You left the email field blank!");
validate = false;
}
else if (e.match(illegalChars))
{
$("#ErrorEmail").text("ILEGAL CHARECTORS DETECTED EXTERMINATE");
validate = false;
}
}
function validateFirstName()
{
var f = document.forms["NewUser"]["fName"].value;
var fLength = f.length;
var illegalChars = /\W/;
if(fLength > 20)
{
$("#ErrorFname").text("First Name has a max of 20 characters");
validate = false;
}
else if (illegalChars.test(f))
{
$("#ErrorFname").text("Numbers,letter and underscores in first name only");
validate = false;
}
}
function validateLastName()
{
var l = document.forms["NewUser"]["lName"].value;
var lLength = l.length;
var illegalChars = /\W/;
if(lLength > 100)
{
$("#ErrorLname").text("Last Name has a max of 100 characters");
validate = false;
}
else if (illegalChars.test(f))
{
$("#ErrorLname").text("Numbers,letter and underscores in last name only");
validate = false;
}
}
function validateForm()
{
validateUserName();
validatePassword();
validateEmail();
validateFirstName();
validateLastName();
return validate;
}
You need to access all the fields and check if the field is valid r not. If the field is valid skip it, otherwise put the field in an array. When all the fields have been checked, then display the error fields from the array all at one time.
Related
I'm trying to apply form validation using js,the problem I'm facing is the form always submits no matter what errors are shown in the form.
the form contains 6 fields: username,email,password,retype_pass, first_name,last_name.
the js code is like this:
$(function checkForBlank() {
$("#username_err_msg").hide();
$("#email_err_msg").hide();
$("#pwd_err_msg").hide();
$("#confirm_pwd_err_msg").hide();
$("#fname_err_msg").hide();
$("#lname_err_msg").hide();
var username_err = false;
var email_err = false;
var pwd_err_msg = false;
var confirm_pwd_err_msg = false;
var fname_err = false;
var lname_err = false;
$("#userName").focusout(function() {
check_userName();
});
$("#inputEmail").focusout(function() {
check_email();
});
$("#password").focusout(function() {
check_pwd();
});
$("#inputConfirmPassword").focusout(function() {
check_pwd_conf();
});
$("#inputFirstName").focusout(function() {
check_fname();
});
$("#inputLastName").focusout(function() {
check_lname();
});
function check_userName() {
var username_length = $("#userName").val().length;
if (username_length < 5 || username_length > 20) {
$("#username_err_msg").html("Username must be between 5 and 20 characters ! ");
$("#username_err_msg").show();
username_err = true;
} else {
$("#username_err_msg").hide();
}
}
function check_pwd() {
var pass = $("#password").val();
var pass_length = $("#password").val().length;
var re = /^[a-zA-Z_0-9#\!#\$\^%&*()+=\-[]\\\';,\.\/\{\}\|\":<>\? ]+$/;
//if pwd is less than 10 and doesnt contain special chars
if (pass_length < 6) {
$("#pwd_err_msg").html("Weak ! ");
$("#pwd_err_msg").show();
pwd_err_msg = true;
} else {
//if pwd is >= 5 or <= 10,and contains special char
if (pass_length >= 6 && pass_length < 9 && !re.test(pass)) {
$("#pwd_err_msg").html("Medium! ");
$("#pwd_err_msg").show();
pwd_err_msg = true;
} else {
//if pwd >11 and contains special char
if (pass_length >= 9 && !re.test(pass)) {
$("#pwd_err_msg").html("Strong! ");
$("#pwd_err_msg").show();
pwd_err_msg = true;
} else {
$("#pwd_err_msg").hide();
}
}
}
}
function check_pwd_conf() {
var pass1 = $("#password").val();
var pass2 = $("#inputConfirmPassword").val();
if (pass1 != pass2) {
$("#confirm_pwd_err_msg").html("Passwords don't match! ");
$("#confirm_pwd_err_msg").show();
pwd_err_msg = true;
} else {
$("#confirm_pwd_err_msg").hide();
}
}
function check_email() {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var email = $("#inputEmail").val();
if (re.test(email)) //valid email address
{
$("#email_err_msg").hide();
} else {
$("#email_err_msg").html("Invalid email address!");
$("#email_err_msg").show();
email_err = true;
}
}
function check_fname() {
var fname_length = $("#inputFirstName").val().length;
var first = $("#inputFirstName").val();
var re = /\d/g;
if (fname_length <= 2 || fname_length > 20) {
$("#fname_err_msg").html("First name must be between 2 and 20 characters ! ");
$("#fname_err_msg").show();
fname_err = true;
} else {
if (re.test(first)) {
$("#fname_err_msg").html("First name must not contain digits ! ");
$("#fname_err_msg").show();
fname_err = true;
} else {
$("#fname_err_msg").hide();
}
}
}
function check_lname() {
var lname_length = $("#inputLastName").val().length;
var sec = $("#inputLastName").val();
var re = /\d/g;
if (lname_length <= 2 || lname_length > 20) {
$("#lname_err_msg").html("Last name must be between 2 and 20 characters ! ");
$("#lname_err_msg").show();
lname_err = true;
} else {
if (re.test(sec)) {
$("#lname_err_msg").html("Last name must not contain digits ! ");
$("#lname_err_msg").show();
lname_err = true;
} else {
$("#lname_err_msg").hide();
}
}
}
});
$(function checkForBlank() {
$("#username_err_msg").hide();
$("#email_err_msg").hide();
$("#pwd_err_msg").hide();
$("#confirm_pwd_err_msg").hide();
$("#fname_err_msg").hide();
$("#lname_err_msg").hide();
var username_err = false;
var email_err = false;
var pwd_err_msg = false;
var confirm_pwd_err_msg = false;
var fname_err = false;
var lname_err = false;
$("#userName").focusout(function() {
check_userName();
});
$("#inputEmail").focusout(function() {
check_email();
});
$("#password").focusout(function() {
check_pwd();
});
$("#inputConfirmPassword").focusout(function() {
check_pwd_conf();
});
$("#inputFirstName").focusout(function() {
check_fname();
});
$("#inputLastName").focusout(function() {
check_lname();
});
function check_userName() {
var username_length = $("#userName").val().length;
if (username_length < 5 || username_length > 20) {
$("#username_err_msg").html("Username must be between 5 and 20 characters ! ");
$("#username_err_msg").show();
username_err = true;
} else {
$("#username_err_msg").hide();
}
}
function check_pwd() {
var pass = $("#password").val();
var pass_length = $("#password").val().length;
var re = /^[a-zA-Z_0-9#\!#\$\^%&*()+=\-[]\\\';,\.\/\{\}\|\":<>\? ]+$/;
//if pwd is less than 10 and doesnt contain special chars
if (pass_length < 6) {
$("#pwd_err_msg").html("Weak ! ");
$("#pwd_err_msg").show();
pwd_err_msg = true;
} else {
//if pwd is >= 5 or <= 10,and contains special char
if (pass_length >= 6 && pass_length < 9 && !re.test(pass)) {
$("#pwd_err_msg").html("Medium! ");
$("#pwd_err_msg").show();
pwd_err_msg = true;
} else {
//if pwd >11 and contains special char
if (pass_length >= 9 && !re.test(pass)) {
$("#pwd_err_msg").html("Strong! ");
$("#pwd_err_msg").show();
pwd_err_msg = true;
} else {
$("#pwd_err_msg").hide();
}
}
}
}
function check_pwd_conf() {
var pass1 = $("#password").val();
var pass2 = $("#inputConfirmPassword").val();
if (pass1 != pass2) {
$("#confirm_pwd_err_msg").html("Passwords don't match! ");
$("#confirm_pwd_err_msg").show();
pwd_err_msg = true;
} else {
$("#confirm_pwd_err_msg").hide();
}
}
function check_email() {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var email = $("#inputEmail").val();
if (re.test(email)) //valid email address
{
$("#email_err_msg").hide();
} else {
$("#email_err_msg").html("Invalid email address!");
$("#email_err_msg").show();
email_err = true;
}
}
function check_fname() {
var fname_length = $("#inputFirstName").val().length;
var first = $("#inputFirstName").val();
var re = /\d/g;
if (fname_length <= 2 || fname_length > 20) {
$("#fname_err_msg").html("First name must be between 2 and 20 characters ! ");
$("#fname_err_msg").show();
fname_err = true;
} else {
if (re.test(first)) {
$("#fname_err_msg").html("First name must not contain digits ! ");
$("#fname_err_msg").show();
fname_err = true;
} else {
$("#fname_err_msg").hide();
}
}
}
function check_lname() {
var lname_length = $("#inputLastName").val().length;
var sec = $("#inputLastName").val();
var re = /\d/g;
if (lname_length <= 2 || lname_length > 20) {
$("#lname_err_msg").html("Last name must be between 2 and 20 characters ! ");
$("#lname_err_msg").show();
lname_err = true;
} else {
if (re.test(sec)) {
$("#lname_err_msg").html("Last name must not contain digits ! ");
$("#lname_err_msg").show();
lname_err = true;
} else {
$("#lname_err_msg").hide();
}
}
}
});
Download the js file here : https://onionfiles.com/file/HGGaFR2G
and include it in, then try this
$().ready(function() {
// validate form on keyup and submit
$("#FORMID").validate({
rules: {
username: "required",
email: "required",
password: "required",
retype_pass: {
required: true,
equalTo:"#password"
}
first_name: "required",
last_name: "required"
},
messages: {
username: "Please enter Username",
email : "Please enter a valid Email",
password: "Please enter a password",
retype_pass: {
required: "Please confirm your password",
equalTo: "Please enter the same password as above"
},
first_name: "Please enter first name",
last_name: "Please enter last name"
}
});
});
A quick fix from your code will be the following.
(function() {
$("#username_err_msg").hide();
$("#email_err_msg").hide();
$("#pwd_err_msg").hide();
$("#confirm_pwd_err_msg").hide();
$("#fname_err_msg").hide();
$("#lname_err_msg").hide();
var username_err = false;
var email_err = false;
var pwd_err_msg = false;
var confirm_pwd_err_msg = false;
var fname_err = false;
var lname_err = false;
$("#userName").focusout(function() {
check_userName();
});
$("#inputEmail").focusout(function() {
check_email();
});
$("#password").focusout(function() {
check_pwd();
});
$("#inputConfirmPassword").focusout(function() {
check_pwd_conf();
});
$("#inputFirstName").focusout(function() {
check_fname();
});
$("#inputLastName").focusout(function() {
check_lname();
});
$("#formId").on("submit", checkForBlank);
function check_userName() {
var username_length = $("#userName").val().length;
if (username_length < 5 || username_length > 20) {
$("#username_err_msg").html("Username must be between 5 and 20 characters ! ");
$("#username_err_msg").show();
username_err = true;
} else {
$("#username_err_msg").hide();
username_err = false;
}
}
function check_pwd() {
var pass = $("#password").val();
var pass_length = $("#password").val().length;
//var re = /^[a-zA-Z_0-9#\!#\$\^%&*()+=\-[]\\\';,\.\/\{\}\|\":<>\? ]+$/;
var re = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[$#$!%*#?&])[A-Za-z\d$#$!%*#?&]{8,}$/;
//if pwd is less than 10 and doesnt contain special chars
if (pass_length < 6) {
$("#pwd_err_msg").html("Weak ! ");
$("#pwd_err_msg").show();
pwd_err_msg = true;
} else {
//if pwd is >= 5 or <= 10,and contains special char
if (pass_length >= 6 && pass_length < 9 && !re.test(pass)) {
$("#pwd_err_msg").html("Medium! ");
$("#pwd_err_msg").show();
pwd_err_msg = true;
} else {
//if pwd >11 and contains special char
if (pass_length >= 9 && !re.test(pass)) {
$("#pwd_err_msg").html("Strong! ");
$("#pwd_err_msg").show();
pwd_err_msg = true;
} else {
$("#pwd_err_msg").hide();
pwd_err_msg = false;
}
}
}
}
function check_pwd_conf() {
var pass1 = $("#password").val();
var pass2 = $("#inputConfirmPassword").val();
if (pass1 != pass2 || pass2.length === 0) {
$("#confirm_pwd_err_msg").html("Passwords don't match! ");
$("#confirm_pwd_err_msg").show();
confirm_pwd_err_msg = true;
} else {
$("#confirm_pwd_err_msg").hide();
confirm_pwd_err_msg = false;
}
}
function check_email() {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var email = $("#inputEmail").val();
if (re.test(email)) //valid email address
{
$("#email_err_msg").hide();
email_err = false;
} else {
$("#email_err_msg").html("Invalid email address!");
$("#email_err_msg").show();
email_err = true;
}
}
function check_fname() {
var fname_length = $("#inputFirstName").val().length;
var first = $("#inputFirstName").val();
var re = /\d/g;
if (fname_length <= 2 || fname_length > 20) {
$("#fname_err_msg").html("First name must be between 2 and 20 characters ! ");
$("#fname_err_msg").show();
fname_err = true;
} else {
if (re.test(first)) {
$("#fname_err_msg").html("First name must not contain digits ! ");
$("#fname_err_msg").show();
fname_err = true;
} else {
$("#fname_err_msg").hide();
fname_err = false;
}
}
}
function check_lname() {
var lname_length = $("#inputLastName").val().length;
var sec = $("#inputLastName").val();
var re = /\d/g;
if (lname_length <= 2 || lname_length > 20) {
$("#lname_err_msg").html("Last name must be between 2 and 20 characters ! ");
$("#lname_err_msg").show();
lname_err = true;
} else {
if (re.test(sec)) {
$("#lname_err_msg").html("Last name must not contain digits ! ");
$("#lname_err_msg").show();
lname_err = true;
} else {
$("#lname_err_msg").hide();
lname_err = false;
}
}
}
function checkForBlank(e) {
check_userName();
check_email();
check_pwd();
check_pwd_conf();
check_fname();
check_lname();
if(username_err || email_err || pwd_err_msg || confirm_pwd_err_msg || fname_err || lname_err) {
e.preventDefault();
}
}
}());
I have changed the checkForBlank function. I have attached it to the form submit event and checked for any errors inside it. Then prevented form submission if any errors found.
But I think the whole code needs to be refactored to reduce code duplication.
Update:
I have made changes to the above code. Here is the working jsfiddle.
I have a form with inputs
Fist name
Last name
Password
Etc
Current my validation works one by one. I would like to integrate them into one pop up box.
Example currently:
All not filled up; upon submission it would pop up First name not filled. I want it to be First name not filled, last name not filled etc
function validateForm() {
var x = document.forms["myForm"]["firstname"].value;
if (x == null || x == "") {
alert("First Name must be filled out");
return false;
}
var x = document.forms["myForm"]["lastname"].value;
if (x == null || x == "") {
alert("Last Name must be filled out");
return false;
}
var status = false;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.forms["myForm"]["email"].value.search(emailRegEx) == -1) {
alert("Please enter a valid email address.");
return false;
}
var status = false;
var paswordregex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
if (document.forms["myForm"]["password"].value.search(paswordregex) == -1) {
alert("Please enter a at least 8 alphanumeric characters");
return false;
}
var password = document.getElementById("password").value;
var confirmPassword = document.getElementById("confirmpassword").value;
if (password != confirmPassword) {
alert("Passwords do not match.");
return false;
}
var checkb = document.getElementById('checkboxid');
if (checkb.checked != true) {
alert('Agree to privacy agreement must be checked');
} else {
status = true;
}
return status;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
function validateForm() {
var regexEmail = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var regexMinThree = /^[A-Za-z0-9_ ]{3,13}$/;
var userFirstName = $.trim($('.firstName').val());
var userLastName = $.trim($('.lastName').val());
var userEmail = $.trim($('.email').val());
var userPassword = $.trim($('.password').val());
var msg = '';
if(!regexMinThree.test(userFirstName)) {
msg = 'FirstName, ';
} else {
msg = '';
}
if(!regexMinThree.test(userLastName)) {
msg = msg+'LastName, ';
} else {
msg = msg+'';
}
if(!regexEmail.test(userEmail)) {
msg = msg+'Email, ';
} else {
msg = msg+'';
}
if(!regexMinThree.test(userPassword)) {
msg = msg+'Password, ';
} else {
msg = msg+'';
}
if(!regexMinThree.test(userPassword) || !regexEmail.test(userEmail) || !regexMinThree.test(userLastName) || !regexMinThree.test(userFirstName)) {
msg = msg+'not filled correctly.';
alert(msg);
}
}
</script>
<form class="userRegistrationForm" onsubmit="return false;" method="post">
<input type="text" class="firstName" placeholder ="FirstName"/>
<input type="text" class="lastName" placeholder ="LastName"/>
<input type="email" class="email" placeholder ="Email"/>
<input type="password" class="password" placeholder ="Password"/>
<button type="submit" onclick="validateForm()" class="userRegistration">Submit</button>
</form>
Add a flag called error and a string called errorMessage, then in each if statement, if there is an error, make error = true and append error message.
Then when submitted, if error == true, alert errorMessage
You can add an <ul> in your html form where you want to show errors
Example
<ul class="errorContainer"></ul>
Then JS
function validateForm() {
var errors = "";
var x = document.forms["myForm"]["firstname"].value;
if (x == null || x == "") {
errors +="<li>First Name must be filled out</li>";
}
var x = document.forms["myForm"]["lastname"].value;
if (x == null || x == "") {
errors +="<li>Last Name must be filled out</li>";
}
var status = false;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.forms["myForm"]["email"].value.search(emailRegEx) == -1) {
errors +="<li>Please enter a valid email address.</li>";
}
var status = false;
var paswordregex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
if (document.forms["myForm"]["password"].value.search(paswordregex) == -1) {
errors +="<li>Please enter a at least 8 alphanumeric characters</li>";
}
var password = document.getElementById("password").value;
var confirmPassword = document.getElementById("confirmpassword").value;
if (password != confirmPassword) {
errors +="<li>Passwords do not match.</li>";
}
var checkb = document.getElementById('checkboxid');
if (checkb.checked != true) {
errors +="<li>Agree to privacy agreement must be checked</li>";
}
if(errors!="")
{
$(".errorContainer").html(errors);
return false;
} else {
status = true;
return status;
}
}
I want to validate my form, if any of the input field is blank, the error warning will show beside the blank input field. The error message must be comes out all at one time for the blank input, not show one by one. How to do this?
Below is my javascript code :
function doValidate()
{
var x=document.forms["form"]["fullname"].value;
if (x==null || x=="")
{
document.getElementById('error1').innerHTML="Full name is required!";
return false;
}
var y=document.forms["form"]["uid"].value;
if (y==null || y=="")
{
document.getElementById('error2').innerHTML="Username is required!";
return false;
}
var z=document.forms["form"]["pwd"].value;
if (z==null || z=="")
{
document.getElementById('error3').innerHTML="Password is required!";
return false;
}
var a=document.forms["form"]["pwd2"].value;
if (a==null || a=="")
{
document.getElementById('error4').innerHTML="Please re-enter your password!";
return false;
}
var pwd = document.getElementById("pwd").value;
var pwd2 = document.getElementById("pwd2").value;
if(pwd != pwd2){
alert('Wrong confirm password!');
return false;
}
var b=document.forms["form"]["role"].value;
if (b==null || b=="Please select...")
{
document.getElementById('error5').innerHTML="Please select user role!";
return false;
}
}
You should start your function with var ok = true, and in each if-block, instead of having return false, you should set ok = false. At the end, return ok.
Here's what that might look like:
function doValidate() {
var ok = true;
var form = document.forms.form;
var fullname = form.fullname.value;
if (fullname == null || fullname == "") {
document.getElementById('error1').innerHTML = "Full name is required!";
ok = false;
}
var uid = form.uid.value;
if (uid == null || uid == "") {
document.getElementById('error2').innerHTML = "Username is required!";
ok = false;
}
var pwd = form.pwd.value;
if (pwd == null || pwd == "") {
document.getElementById('error3').innerHTML = "Password is required!";
ok = false;
}
var pwd2 = form.pwd2.value;
if (pwd2 == null || pwd2 == "") {
document.getElementById('error4').innerHTML = "Please re-enter your password!";
ok = false;
} else if (pwd != pwd2) {
document.getElementById('error4').innerHTML = "Wrong confirm password!";
ok = false;
}
var role = form.role.value;
if (role == null || role == "Please select...") {
document.getElementById('error5').innerHTML = "Please select user role!";
ok = false;
}
return ok;
}
(I've taken the liberty of changing to a more consistent formatting style, improving some variable-names, simplifying some access patterns, and replacing an alert with an inline error message like the others.)
I am having a hard time trying to do a correct form validation. I have Name, Email, and Phone Number fields. I implemented the validation check for all of them and when I click on the submit query, it returns email as false, but not anything else. It also will still submit the form. How do I fix this?
JSFiddle: http://jsfiddle.net/GVQpL/
JavaScript Code:
function validateForm(/*fullName, email, phoneNumber*/)
{
//-------------------------NAME VALIDATION-----------------------------//
var fullNameV = document.forms["queryForm"]["fullName"].value;
if (fullNameV == null || fullNameV == "")
{
alert("Name must be filled out!");
return false;
}
else if(fullNameV.indexOf(" ") <= fullNameV.length)
{
alert("Not a valid name");
return false;
}
//-------------------------EMAIL VALIDATION-----------------------------//
var emailV = document.forms["queryForm"]["email"].value;
if (emailV == null || emailV == "")
{
alert("Email must be filled out!");
return false;
}
var atpos = emailV.indexOf("#");
var dotpos = emailV.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length)
{
alert("Not a valid e-mail address");
return false;
}
//-------------------------PHONE # VALIDATION-----------------------------//
var phoneNumberV = document.forms["queryForm"]["phoneNumber"].value;
if (phoneNumberV == null || phoneNumberV == "")
{
alert("Phone Number must be filled out!");
return false;
}
var error = "";
var stripped = phoneNumberV.replace(/[\(\)\.\-\ ]/g, '');
if (phoneNumberV == "")
{
error = alert("You didn't enter a phone number.\n");
phoneNumberV.style.background = 'Yellow';
}
else if (isNaN(parseInt(stripped)))
{
error = alert("The phone number contains illegal characters.\n");
phoneNumberV.style.background = 'Yellow';
}
else if (!(stripped.length == 10))
{
error = alert("The phone number is the wrong length. Make sure you included an area code.\n");
phoneNumberV.style.background = 'Yellow';
}
return error;
}
Update your fiddle's html for the function to be called onsubmit="return validateForm()" and removed the required="required" changed your function to work, you can see it here:
http://jsfiddle.net/GVQpL/3/
function validateForm(/*fullName, email, phoneNumber*/)
{
//-------------------------NAME VALIDATION-----------------------------//
var fullNameV = document.forms["queryForm"]["fullName"].value;
if (fullNameV == null || fullNameV == "")
{
alert("Name must be filled out!");
document.forms["queryForm"]["fullName"].focus();
return false;
}
else if(fullNameV.indexOf(" ") >= fullNameV.length)
{
alert("Not a valid name");
document.forms["queryForm"]["fullName"].focus();
return false;
}
//-------------------------EMAIL VALIDATION-----------------------------//
var emailV = document.forms["queryForm"]["email"].value;
if (emailV == null || emailV == "")
{
alert("Email must be filled out!");
document.forms["queryForm"]["email"].focus();
return false;
}
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test(emailV)){
alert("Not a valid e-mail address");
document.forms["queryForm"]["email"].focus();
return false;
}
//-------------------------PHONE # VALIDATION-----------------------------//
var phoneNumberV = document.forms["queryForm"]["phoneNumber"].value;
if (phoneNumberV == null || phoneNumberV == "")
{
alert("Phone Number must be filled out!");
document.forms["queryForm"]["phoneNumber"].focus();
return false;
}
var error = "";
var stripped = phoneNumberV.replace(/[\(\)\.\-\ ]/g, '');
if (phoneNumberV == "")
{
alert("You didn't enter a phone number.\n");
document.forms["queryForm"]["phoneNumber"].focus()
document.forms["queryForm"]["phoneNumber"].style.background = 'Yellow';
return false;
}
else if (isNaN(parseInt(stripped)))
{
alert("The phone number contains illegal characters.\n");
document.forms["queryForm"]["phoneNumber"].focus();
document.forms["queryForm"]["phoneNumber"].style.background = 'Yellow';
return false;
}
else if (!(stripped.length == 10))
{
alert("The phone number is the wrong length. Make sure you included an area code.\n");
document.forms["queryForm"]["phoneNumber"].focus();
document.forms["queryForm"]["phoneNumber"].style.background = 'Yellow';
return false;
}
if(!confirm('Are you sure you want to submit your DSLR query?')){
return false;
}
return true;
}
My goal is this:
Check if email and name are empty. If so, give 'Enter email or name' alert.
If they do, check for an # in email If none is found, give 'Bad email' alert.
Check if email and name contain any letters, if they do, give 'Success' alert
function test(email, name){
if(email=="" || name == "") {
alert("Enter mail or name");}
return false;
if(email.indexOf("#") == -1){
alert("Bad email");}
return false;
var a = email.length;
var b = name.length;
if(a==>0, b==>0){
alert("Message sent");}
return true;
}
This is what I've come up with so far, but it isn't working. I'm quite new at javascript so maybe you guys could tell me what I've done wrong?
The problem you're having is the close bracket is in the wrong place. You have it at the end of your alert statement and you probably want the return to be included with your if statement. if this is the case then change it to be:
function test(email, name){
if(email=="" || name == "") {
alert("Enter mail or name");
return false;
}
if(email.indexOf("#") == -1){
alert("Bad email");
return false;
}
var a = email.length;
var b = name.length;
if(a > 0 && b > 0){
alert("Message sent");
return true;
}
}
A better way to do the same thing would be because that way you're not checking the variables for length and size twice:
function test(email, name) {
var a = email.length;
var b = name.length;
if ( a > 0 && b > 0 ) {
// ignore 0 because email addresses shouldn't start with #
if ( email.indexOf("#") > 0 ) {
alert("Message sent");
return true;
}
else {
alert("Bad email");
return false;
}
}
else {
alert("Enter mail or name");
return false;
}
}
Try this JSFiddle that seems to fit your needs http://jsfiddle.net/9nF5W/
function test(email, name) {
if (email == "" || name == "") {
alert("Enter mail or name");
return false;
}
if (email.indexOf("#") == -1) {
alert("Bad email");
return false;
}
var a = email.length;
var b = name.length;
if (a > 0 && b > 0) {
alert("Message sent");
}
return true;
}
test('tes#t', 'test');
I think there is an other mistake than the returns statements in "if(a==>0, b==>0){" by the way.