/    Sign up×
Community /Pin to ProfileBookmark

HTML + Javascript validation

disclaimer: Im fairly new to web page coding.

I am trying to do some basic form validation. I have 3 fields (firstName, lastName, E-Mail, Comment). The form onSubmit calls my javascript validation function like so.

<form class=”contactUs” name=”ContactUs” action=”mailto:[email protected]” method=”post” onSubmit=”return validate(this);” >

The validate function is here.

function validate(form)
{
//validate the individual elements to see if they are properly entered
if(form.firstName.value==””)
{
alert(“First Name is a required field, please enter your first name.”);
return false;
}
else if (form.lastName.value==””)
{
alert(“Last Name is a required field, please enter your last name.”);
return false;
}
else if (form.E-Mail.value.indexOf(“@”)==-1 || form.E-Mail.value.indexOf(“@”)==0 || form.E-Mail.value==””)
{
alert(“E-Mail Address is required, please enter your E-Mail address”);
return false;
}
return false;
}

The first and last name validation simply make sure that at least one character has been entered before it allows the form to submit. This part of the code works perfectly. The email portion is the part that is not working. If I take the email validation section and move it into its own javascript file, it works with onBlur. For some reason the same code refuses to work in this file. Is there a better way to do this? Any help you can offer would be appreciated.

to post a comment
JavaScript

12 Comments(s)

Copy linkTweet thisAlerts:
@ryanbutlerMar 10.2010 — I think you want to adjust the double pipes for &&, b/c you want to ensure none of those conditions are true. The pipes are OR stmts, meaning that as long as one of those conditions is true it will succeed. Whereas with &&, all those conditions have to be met before it can succeed.
Copy linkTweet thisAlerts:
@bigblondguyauthorMar 10.2010 — thanks for the reply ryan, but I actually do want the double pipes. If one single expression evaluates to true in the if it means the email address was entered incorrectly, and thus I need to stop the form from submitting and alert the user as to the issue.

it seems that the problem was with a completely different line of code I was trying to enter. There is some sort of error in my logic that is making it so the whole javascript file is completely ignored. The line happens to be where I check to see if the @ symbol comes before the . symbol in the email address.

[CODE] else if (form.email.value.indexOf(".") <= (form.email.value.indexOf("@"))
{
alert("E-Mail Address is required, please enter your E-Mail address");
return false;
}[/CODE]


All I am trying to do with this line is check to see a couple of conditions. If the @ and . are at the same index, it means neither was entered (result of -1). If the period comes before the @ symbol, we evaluate to true and exectute the alert statement and return false. Otherwise, we evaluate to true and move along. Im wondering what part of this code is invalid making it so the entire javascript file will not work with it.
Copy linkTweet thisAlerts:
@ryanbutlerMar 11.2010 — It seems like you need a regex to pull that off and I absolutely suck at those (plus it's been about three yrs since I've tried one).
Copy linkTweet thisAlerts:
@bigblondguyauthorMar 11.2010 — [CODE]//validation function for form
function validate(form)
{
//declare local variables
var indexAt = form.email.value.indexOf("@");
var indexDot = form.email.value.indexOf(".");

//validate the first name
if(form.firstName.value=="")
{
alert("First Name is a required field, please enter your first name.");
form.firstName.focus();
return false;
}

//validate the last name
else if (form.lastName.value=="")
{
alert("Last Name is a required field, please enter your last name.");
form.lastName.focus();
return false;
}

//validate the email address
else if (form.email.value.indexOf("@")==-1 || form.email.value.indexOf("@")==0 || form.email.value=="" || form.email.value.indexOf('.')==-1 || form.email.value.indexOf(".")==0)
{
alert("E-Mail Address is required, please enter your E-Mail address");
form.email.focus();
return false;
}

//validate the email address
else if (indexDot <= indexAt)
{
alert("E-Mail Address is required, please enter your E-Mail address");
form.email.focus();
return false;
}

//verify whether the default string is in the comment box
else if (form.Comment.value=="Comment")
{
alert("A Comment is required, please enter a meaningful Comment");
form.Comment.focus();
return false;
}

//verify that the comment box is not empty
else if (form.Comment.value.replace(/[srn]/g,"")=="")
{
alert("A Comment is required, please enter a meaningful Comment");
form.Comment.focus();
return false;
}

//valid entry, submit form
return true;
}[/CODE]


This function can be used for validation. It worky worky.
Copy linkTweet thisAlerts:
@tirnaMar 12.2010 — Just a suggestion while playing devil's advocate on your validation script.

It appears that since your validation only checks the first and last names to see if they contain at least 1 character, then a user could simply enter a blank space resulting in the JS variables equating to " " and so pass the validation test for the first and last names.

Maybe try trimming the name strings by removing any leading or trailing blank spaces and if the trimmed string length is still > 0, then loop through each character in the trimmed name string to see if it is a valid character which you can specify in your javascript.

If for some reason you want to allow leading and trailing spaces then you need to check if there are any non-blank space characters in the name strings.

This should help make your validation more robust and give you 'cleaner' data to eventually store in your database or wherever.
Copy linkTweet thisAlerts:
@bigblondguyauthorMar 12.2010 — I forgot to mention that. I actually call a function onBlur that removes white spaces.

[CODE]//simple function to remove spaces
function removeSpaces(string) {
return string.split(' ').join('');
}
[/CODE]


Pretty simple. So I do take into account that particular scenario. Since the first and last names are usually just one word, it works ok for now. Eventually im going to need to update it to handle first names like "Billy Joe Bob" and "Betty Sue", ill end up using the trim method for that. I do also need to validate that correct values are being entered for the characters, not just random garbage. Thank you very much for the ideas, every little bit helps.
Copy linkTweet thisAlerts:
@bigblondguyauthorMar 12.2010 — I went ahead and updated my validation script to reflect searching the first and last names for garbage characters. I will work on implementing something for email tomorrow. Comments there really isnt a whole lot of reason to bother with it, mainly just the first and last names. Here is the new script, any other advice you could offer would be greatly appreciated. The validate function is called onSubmit by the form.

[CODE]//validation function for form
function validate(form)
{
//declare local variables
var invalidExpression = /[$\@\#%^&*()[]+_{}`~=|]/;
var validCheckFirst = form.firstName.value.search(invalidExpression);
var validCheckLast = form.lastName.value.search(invalidExpression);
var indexAt = form.formal.value.indexOf("@");
var indexDot = form.formal.value.indexOf(".");

//validate the first name
if(form.firstName.value=="")
{
alert("First Name is a required field, please enter your first name.");
form.firstName.focus();
return false;
}

//validate the last name
else if (form.lastName.value=="")
{
alert("Last Name is a required field, please enter your last name.");
form.lastName.focus();
return false;
}

//validate the email address
else if (form.formal.value.indexOf("@")==-1 || form.formal.value.indexOf("@")==0 || form.formal.value=="" || form.formal.value.indexOf('.')==-1 || form.formal.value.indexOf(".")==0)
{
alert("E-Mail Address is required, please enter your E-Mail address");
form.formal.focus();
return false;
}

//validate the email address
else if (indexDot <= indexAt)
{
alert("E-Mail Address is required, please enter your E-Mail address");
form.formal.focus();
return false;
}

//verify whether the default string is in the comment box
else if (form.Comment.value=="Comment")
{
alert("A Comment is required, please enter a meaningful Comment");
form.Comment.focus();
return false;
}

//verify that the comment box is not empty
else if (form.Comment.value.replace(/[srn]/g,"")=="")
{
alert("A Comment is required, please enter a meaningful Comment");
form.Comment.focus();
return false;
}

//validate that illegal characters have not been entered into first name
else if (validCheckFirst != -1)
{
alert("One or more of the characters entered for First Name are not valid, please re-enter your First Name");
return false;
}

//validate that illegal characters have not been entered into last name
else if (validCheckLast != -1)
{
alert("One or more of the characters entered for Last Name are not valid, please re-enter your Last Name");
return false;
}

//valid entry, submit form
return true;
}[/CODE]


I also went ahead and updated the removeSpaces function to use trim versus split and join. Both functions are now much more robust and working. The removeSpaces function is called onBlur by the individual input boxes.

[CODE]//simple function to remove spaces
function removeSpaces(string)
{
return String.trim(string);
}[/CODE]
Copy linkTweet thisAlerts:
@bigblondguyauthorMar 12.2010 — I went ahead and updated my validation script to reflect searching the first and last names for garbage characters. I will work on implementing something for email tomorrow. Comments there really isnt a whole lot of reason to bother with it, mainly just the first and last names. Here is the new script, any other advice you could offer would be greatly appreciated. The validate function is called onSubmit by the form.

[CODE]//validation function for form
function validate(form)
{
//declare local variables
var invalidExpression = /[$\@\#&#37;^&*()[]+_{}`~=|]/;
var validCheckFirst = form.firstName.value.search(invalidExpression);
var validCheckLast = form.lastName.value.search(invalidExpression);
var indexAt = form.formal.value.indexOf("@");
var indexDot = form.formal.value.indexOf(".");

//validate the first name
if(form.firstName.value=="")
{
alert("First Name is a required field, please enter your first name.");
form.firstName.focus();
return false;
}

//validate the last name
else if (form.lastName.value=="")
{
alert("Last Name is a required field, please enter your last name.");
form.lastName.focus();
return false;
}

//validate the email address
else if (form.formal.value.indexOf("@")==-1 || form.formal.value.indexOf("@")==0 || form.formal.value=="" || form.formal.value.indexOf('.')==-1 || form.formal.value.indexOf(".")==0)
{
alert("E-Mail Address is required, please enter your E-Mail address");
form.formal.focus();
return false;
}

//validate the email address
else if (indexDot <= indexAt)
{
alert("E-Mail Address is required, please enter your E-Mail address");
form.formal.focus();
return false;
}

//verify whether the default string is in the comment box
else if (form.Comment.value=="Comment")
{
alert("A Comment is required, please enter a meaningful Comment");
form.Comment.focus();
return false;
}

//verify that the comment box is not empty
else if (form.Comment.value.replace(/[srn]/g,"")=="")
{
alert("A Comment is required, please enter a meaningful Comment");
form.Comment.focus();
return false;
}

//validate that illegal characters have not been entered into first name
else if (validCheckFirst != -1)
{
alert("One or more of the characters entered for First Name are not valid, please re-enter your First Name");
return false;
}

//validate that illegal characters have not been entered into last name
else if (validCheckLast != -1)
{
alert("One or more of the characters entered for Last Name are not valid, please re-enter your Last Name");
return false;
}

//valid entry, submit form
return true;
}[/CODE]


I also went ahead and updated the removeSpaces function to use trim versus split and join. Both functions are now much more robust and working. The removeSpaces function is called onBlur by the individual input boxes.

[CODE]//simple function to remove spaces
function removeSpaces(string)
{
return String.trim(string);
}[/CODE]


//edit

My perfect girlfriend who knows nothing about coding just made me realize that there is one scenario I dont take into account. What happens if a person has a period in their email aside from the one after the @ symbol? I will have to update my validation function to check for this, I will probably have to use another case statement to keep searching if the period is found before the @ to make sure there is another period AFTER the @.

example: [email][email protected][/email]

[CODE]//this will have to be at the end of my validation function, the only way to return true is to validate all previous statements and finish in this loop
for (i=0; i < endOfString; i++)
{
if (found and before @ symbol)
{
keep searching for a period;
}
else if (found and after @ symbol)
{
return true;
else //end of string reached and no more periods
{
return false
}
} [/CODE]


This is only the beginning of the idea. It is late and I am tired, ill work on it some more tomorrow. Have a great night and thanks for all of the awesome advice.
Copy linkTweet thisAlerts:
@tirnaMar 12.2010 — Looking a lot more robust now ?

But, don't forget in your validation function just before you return true, to write back to their original text boxes any values that you have trimmed or corrected in any way during validation.

If you don't, then when the form data is sent, the receiving server side script will receive the untrimmed, uncorrected data.

Finally, a minor point, maybe consider changing all the text strings to either lower or upper case (using .toLowerCase() or .toUppercase() ) during validation to have consitency of data formatting in your database or whatever. Whenever you eventually retrieve the data from the db you can always reformat it to what you need on the fly before displaying it on your web page.
Copy linkTweet thisAlerts:
@tirnaMar 12.2010 — I might be able to save you some time.

Below is the JS I use to validate email address formats.

validateEmailAddress() returns either tru or false

It will reject the overwhelming majority of invalid email address formats.

Have a play with it. If you like it, feel free to use it.

[CODE]
/*
This function validates an email address' format.

It does not validate whether an email address is real or not.
*/
function validateEmailAddress(emailAddress)
{

if(emailAddress == "") return true; //assume email address is not mandatory

//reject email address if there is no @ or if it contains spaces

if(emailAddress.indexOf("@") == -1 || emailAddress.indexOf(" ") != -1)
{
return false;
}
//reject the email address if there is more than 1 @

var count = 0;

for(var i=0; i < emailAddress.length; i=i+1)
{
if(emailAddress.charAt(i) == "@") {
count = count + 1;
}

if(count > 1)
{
return false;
}
}

//reject the email address if it starts or ends with a dot or an @

if(emailAddress.substring(0,1) == "." || emailAddress.substring(emailAddress.length-1) == "."
|| emailAddress.substring(0,1) == "@" || emailAddress.substring(emailAddress.length-1) == "@")
{
return false;
}

//reject the email address if there is a dot after the @

if(emailAddress.charAt((emailAddress.indexOf("@")+1)) == ".")
{
return false;
}

//now split the email address at the @ synbol

//emailPart[0] contains string to the left of @
//emailPart[1] contains string to the right of @

var emailPart = emailAddress.split("@");

//reject email address if there are 2 dots in a row to the right of @

for(var i=0; i < emailPart[1].length-1; i=i+1)
{
if(emailPart[1].charAt(i) == "." && emailPart[1].charAt(i+1) == ".")
{
return false;
}
}

//split the string on the right of the @ using a dot delimeter

var emailRightPart = emailPart[1].split(".");

//reject email address if there are less than 2 tokens on the right of @

if(emailRightPart.length < 2)
{
return false;
}
//check each right side token (domain, sub domain tokens etc) for valid characters
//reject email if a token contains invalid chars

var isTokenValid = false;

for(var i= 0; i < emailRightPart.length; i=i+1)
{
isTokenValid = validateTokenChars(emailRightPart[i]);

if(isTokenValid == false)
{
return false;
}
}

//check the left side token (username part of email address) for valid chars

isTokenValid = false;

isTokenValid = validateTokenChars(emailPart[0]);

if(isTokenValid == false) //reject email if token contains invalid chars
{
return false;
}

// at this point the email address is valid

return true;

} // end of validateEmailAddress()
//============================
//this function is called by validateEmailAddress()
function validateTokenChars(strToken)
{
strToken = strToken.toLowerCase();
isTokenOK = true

for(var i=0; i < strToken.length; i=i+1)
{
if(strToken.charAt(i) != "0" && strToken.charAt(i) != "1" && strToken.charAt(i) != "2" && strToken.charAt(i) != "3" && strToken.charAt(i) != "4" &&
strToken.charAt(i) != "5" && strToken.charAt(i) != "6" && strToken.charAt(i) != "7" && strToken.charAt(i) != "8" && strToken.charAt(i) != "9" &&
strToken.charAt(i) != "a" && strToken.charAt(i) != "b" && strToken.charAt(i) != "c" && strToken.charAt(i) != "d" && strToken.charAt(i) != "e" &&
strToken.charAt(i) != "f" && strToken.charAt(i) != "g" && strToken.charAt(i) != "h" && strToken.charAt(i) != "i" && strToken.charAt(i) != "j" &&
strToken.charAt(i) != "k" && strToken.charAt(i) != "l" && strToken.charAt(i) != "m" && strToken.charAt(i) != "n" && strToken.charAt(i) != "o" &&
strToken.charAt(i) != "p" && strToken.charAt(i) != "q" && strToken.charAt(i) != "r" && strToken.charAt(i) != "s" && strToken.charAt(i) != "t" &&
strToken.charAt(i) != "u" && strToken.charAt(i) != "v" && strToken.charAt(i) != "w" && strToken.charAt(i) != "x" && strToken.charAt(i) != "y" &&
strToken.charAt(i) != "z" && strToken.charAt(i) != "." && strToken.charAt(i) != "&" && strToken.charAt(i) != "*" && strToken.charAt(i) != "+" &&
strToken.charAt(i) != "-" && strToken.charAt(i) != "/" && strToken.charAt(i) != "=" && strToken.charAt(i) != "?" && strToken.charAt(i) != "^" &&
strToken.charAt(i) != "_" && strToken.charAt(i) != "{" && strToken.charAt(i) != "}" )
{
isTokenOK = false;

i = strToken.length; //jump out of FOR loop
}
}

return isTokenOK;
}
//====================================

[/CODE]
Copy linkTweet thisAlerts:
@bigblondguyauthorMar 13.2010 — I went ahead and looked at your code, realizing how many of those test cases I probably would have missed without your help. I modified the code very slightly (mainly in alerts that I will update to a better method at some later point), and put it into the same file as the rest of my checks so all of them will be run when the submit button is pressed for that form. I suppose ideally I would want seperate validation files for later expansion, but currently I am not an advanced enough user to know certain tricks. Perhaps you know the answer to this.

If one of the onBlur events fails, disable the submit button until the problem is corrected?

my ideal setup would be the user enters his information, initially the submit button will start out greyed out. Once all the fields have been filled in correctly, the submit button will become active and the user is freely able to submit his information. Im honestly not even sure that is possible, but if it were that would be a nice little touch to add.

[CODE]function validateFormData(form)
{
//declare local variables
var invalidExpression = /[$\@\#%^&*()[]+_{}`~=|]/;
var validCheckFirst = form.firstName.value.search(invalidExpression);
var validCheckLast = form.lastName.value.search(invalidExpression);

//validate the first name
if(form.firstName.value=="")
{
alert("First Name is a required field, please enter your first name.");
form.firstName.focus();
return false;
}

//validate the last name
else if (form.lastName.value=="")
{
alert("Last Name is a required field, please enter your last name.");
form.lastName.focus();
return false;
}

//validate that illegal characters have not been entered into first name
else if (validCheckFirst != -1)
{
alert("One or more of the characters entered for First Name are not valid, please re-enter your First Name");
return false;
}

//validate that illegal characters have not been entered into last name
else if (validCheckLast != -1)
{
alert("One or more of the characters entered for Last Name are not valid, please re-enter your Last Name");
return false;
}

//verify whether the default string is in the comment box
else if (form.Comment.value=="Comment")
{
alert("A Comment is required, please enter a meaningful Comment");
form.Comment.focus();
return false;
}

//verify that the comment box is not empty
else if (form.Comment.value.replace(/[srn]/g,"")=="")
{
alert("A Comment is required, please enter a meaningful Comment");
form.Comment.focus();
return false;
}

/********Start Code Provided By: Tirna**********/

//reject email address if there is no @ or if it contains spaces
if(form.formal.value.indexOf("@") == -1 || form.formal.value.indexOf(" ") != -1)
{
alert("E-Mail information entered was invalid. Please enter a valid E-Mail address");
form.formal.focus();
return false;
}

//reject the email address if there is more than 1 @
var count = 0;

for(var i=0; i < form.formal.value.length; i=i+1)
{
if(form.formal.value.charAt(i) == "@")
{
count = count + 1;
}

if(count > 1)
{
alert("E-Mail information entered was invalid. Please enter a valid E-Mail address");
form.formal.focus();
return false;
}
}

//reject the email address if it starts or ends with a dot or an @
if(form.formal.value.substring(0,1) == "." || form.formal.value.substring(form.formal.value.length-1) == "." || form.formal.value.substring(0,1) == "@" || form.formal.value.substring(form.formal.value.length-1) == "@")
{
alert("E-Mail information entered was invalid. Please enter a valid E-Mail address");
form.formal.focus();
return false;
}

//reject the email address if there is a dot after the @
if(form.formal.value.charAt((form.formal.value.indexOf("@")+1)) == ".")
{
alert("E-Mail information entered was invalid. Please enter a valid E-Mail address");
form.formal.focus();
return false;
}

//now split the email address at the @ symbol
//emailPart[0] contains string to the left of @
//emailPart[1] contains string to the right of @

var emailPart = form.formal.value.split("@");

//reject email address if there are 2 dots in a row to the right of @
for(var i=0; i < emailPart[1].length-1; i=i+1)
{
if(emailPart[1].charAt(i) == "." && emailPart[1].charAt(i+1) == ".")
{
alert("E-Mail information entered was invalid. Please enter a valid E-Mail address");
form.formal.focus();
return false;
}
}

//split the string on the right of the @ using a dot delimeter
var emailRightPart = emailPart[1].split(".");

//reject email address if there are less than 2 tokens on the right of @
if(emailRightPart.length < 2)
{
alert("E-Mail information entered was invalid. Please enter a valid E-Mail address");
form.formal.focus();
return false;
}

//check each right side token (domain, sub domain tokens etc) for valid characters
//reject email if a token contains invalid chars
var isTokenValid = false;

for(var i= 0; i < emailRightPart.length; i=i+1)
{
isTokenValid = validateTokenChars(emailRightPart[i]);

if(isTokenValid == false)
{
alert("E-Mail information entered was invalid. Please enter a valid E-Mail address");
form.formal.focus();
return false;
}
}

//check the left side token (username part of email address) for valid chars
isTokenValid = false;

isTokenValid = validateTokenChars(emailPart[0]);

if(isTokenValid == false) //reject email if token contains invalid chars
{
alert("E-Mail information entered was invalid. Please enter a valid E-Mail address");
form.formal.focus();
return false;
}

//return showing the email address as valid
return true;

/********End Code Provided By: Tirna**********/
}[/CODE]
Copy linkTweet thisAlerts:
@tirnaMar 13.2010 — no problem bigblondguy.

Yes you can disable the submit button if certain conditions are not met or even disable it originally and only enable it when all conditions have been met. You can enable/disable buttons using javascript.

How you handle your forms is totally up to you, but I'll just summarise what I normally do as food for thought.

1) I have the submit button enabled when the form is loaded and an onsubmit event handler function in my <form> tag which validates the form data.

2) If the validation function return true, the form is submitted otherwise I display either the user errors in an alert box or highlight incorrect form entries in red on the web page for the user to fix.

3) The validation function basically works like this:

a) read all the form data into variables.

b) initialise a boolean flag called: var isdataValid = true;

c) initialise a an error msg string:

var msg = "The following inputs are missing or invalid:nn"

d) I then check each form input individually to see if is valid. If it is invalid I set isdataValid = false; and append an error to the error message string.

msg = msg + "Usernamen";

After I have checked all the form input data I then check the value of isDataValid and return true or false to the onsubmit call.

[CODE]
if(isDataValid) {
return true;
} else { //some form data was invalid
alert(msg);
return false;
}
[/CODE]


This way, the user is told of all their errors in a form in one go as opposed to being told one at a time with a separate alert box every time a validation of a particular input fails, which would annoy me no end. I prefer to be told all my input errors in one go.


Anyway, the above is just meant to be food for thought. ?
×

Success!

Help @bigblondguy spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...