JavaScript Form Input Validation and Correction
By Will Bontrager2005-04-12
Form Input Validation and Correction
Your website visitors sometimes type their name in all capital letters. Or all lower case. And when you manually correct the case, there is danger of introducing typographical errors.
This article will show you how to fix that -- and without paying a programmer to modify your CGI program.
And another thing: You know how annoying it is when you click a "submit" button, wait for the next page to appear, and then all you get is the message, "your email address is incorrect!"
Wouldn't it be nice to alert your visitors to errors before they click your submit button? Today you learn how.
Note: This article contains both JavaScript and HTML code. If you are reading this on an HTML-enabled email program, you may need to "view source" for all the code to be visible.
As an alternative, you may view this article in the archives (which will present the code correctly in your browser). Or you may wish to grab the source code from the demonstration page. The archives are at http://willmaster.com/possibilities/archives/ and the demonstration page is at http://willmaster.com/possibilities/demo/formcheck.shtml
JavaScript is line-break sensitive. If you install the code and it doesn't work, your email may have wrapped sensitive lines. Go to one of the URLs in the above paragraph and compare the line breaks.
Here is a skeleton form we will use in this article:
<form name="dForm" method="POST" action="script.cgi">So you have better understanding in case you want to modify your code, let's talk about each part of that element.
Your Name:
<input onBlur="CheckName(document.dForm.name.value)" name="name" type="text">
Your Email Address:
<input onBlur="CheckEmail(document.dForm.email.value)" name="email" type="text">
<input onClick="return ValidateAll()" type="submit" value="Send">
</form>
onBlur="..."
onBlur is JavaScript code which activates what is between the quotes whenever the item blurs. An item blurs when the cursor leaves it, such as when another field or the submit button is clicked.
CheckName()
CheckName() is the name of the function which validates and corrects your visitor's name. (The function name for checking the email address is CheckEmail().) The function must know what data it is to work on, and it finds that out by what's inside the parentheses.
document.dForm.name.value
document
Do not change this. It is a reference to the current web page.
dForm
dForm is the exact name of this form. Ensure it matches what is between the quotes of the name="______" element of your <form... tag.
name
name is the exact name of this particular form field. Ensure it matches what is between the quotes of the name="______" element of your applicable <input... tag.
value
Do not change this. It is a reference to the contents of this particular form field.
With the above, the functions know what data to work on and where to place the results.
The email form field has similar elements.
In the <input... tag with the type="submit" element (the submit button), there is an onClick="return ValidateAll()" element. It checks each form field which is listed in the function. This can seem redundant, because the fields were already checked when they blurred. However, it is possible to get an error message and not fix it. In that case, it will be caught when the user clicks the submit button.
Your situation might not require using both:
To validate the form fields as soon as your visitor is finished typing in each field, but eliminating the validation when the submit button is clicked, keep the onBlur="..." elements and remove the onClick="..." element.
To validate the form fields only when your visitor clicks on the submit button, keep the onClick="..." element and remove the onBlur="..." elements.
Fixing your form is one step. The other step is placing the functions onto your webpage.
Here are the five necessary functions. Place them on your page between the <head> and </head> tags. (The functions are explained below.)
<script language="JavaScript">The above functions depend on each other. ValidateAll() uses CheckName() and CheckEmail(). Both CheckName() and CheckEmail() use StripSpacesFromEnds() and IsItPresent(). IsItPresent() uses StripSpacesFromEnds().
<!--
function ValidateAll()
{
if(CheckName(document.dForm.name.value) == false) return false;
if(CheckEmail(document.dForm.email.value) == false) return false;
return true;
}
function StripSpacesFromEnds(s)
{
// developed by willmaster.com
while((s.indexOf(' ',0) == 0) && (s.length > 1))
{
s = s.substring(1,s.length);
}
while((s.lastIndexOf(' ') == (s.length - 1) && (s.length > 1)))
{
s = s.substring(0,(s.length - 1));
}
if((s.indexOf(' ',0) == 0) && (s.length == 1)) s = '';
return s;
}
function IsItPresent(s,explanation)
{
// developed by willmaster.com
s = StripSpacesFromEnds(s);
if(s.length) return s;
alert('Please enter ' + explanation + '.');
return '';
}
function CheckName(s_name)
{
// developed by willmaster.com
s_name = IsItPresent(s_name,'your name');
if(! s_name) return false;
var i = s_name.indexOf(' ',0);
while(i > -1)
{
s_name = s_name.substring(0,(i + 1)) +
s_name.substring((i + 2),s_name.length);
i = s_name.indexOf(' ',0);
}
s_name = s_name.toLowerCase();
var s = new String(s_name.substring(0,1));
s = s.toUpperCase();
s_name = s + s_name.substring(1,s_name.length);
i = s_name.indexOf(' ',0);
if(i == (s_name.length - 1)) i = -1;
var ts = new String("");
var j = 0;
while(i > -1)
{
i++;
j = i + 1;
s = s_name.substring(i,j);
s = s.toUpperCase();
ts = '';
if(i > 0) ts = s_name.substring(0,i);
s_name = ts + s + s_name.substring(j,s_name.length);
i = s_name.indexOf(' ',j);
if(i == (s_name.length - 1)) i = -1;
}
document.dForm.name.value = s_name;
return true;
}
function CheckEmail(s_email)
{
// developed by willmaster.com
s_email = IsItPresent(s_email,'your email address');
if(! s_email) return false;
var i = s_email.indexOf(' ',0);
while(i > -1)
{
s_email = s_email.substring(0,i) +
s_email.substring((i + 1),s_email.length);
i = s_email.indexOf(' ',0);
}
document.dForm.email.value = s_email;
if((s_email.length < 6) ||
(s_email.indexOf('@',0) < 1) ||
(s_email.lastIndexOf('@') != s_email.indexOf('@',0)) ||
(s_email.lastIndexOf('@') > (s_email.length - 5)) ||
(s_email.lastIndexOf('.') > (s_email.length - 3)) ||
(s_email.lastIndexOf('.') < (s_email.length - 4)) ||
(s_email.indexOf('..',0) > -1) ||
(s_email.indexOf('@.',0) > -1) ||
(s_email.indexOf('.@',0) > -1) ||
(s_email.indexOf(',',0) > -1))
{
alert('The email address "' + s_email + '" is not valid.');
return false;
}
return true;
}
// -->
</script>
StripSpacesFromEnds() does what it's name implies; it removes any leading and trailing spaces from whatever your user typed into the form input field.
IsItPresent() determines whether or not anything has been typed into the form field. First it uses StripSpacesFromEnds(), then it looks to see if anything is left.
CheckEmail() determines whether or not the email address is formatted correctly. First, it uses IsItPresent() to see if anything has been typed into the form field. If not, an error message is delivered. Then it removes any other spaces which might be present. Finally, it checks the email formatting for:
• Must be at least 6 characters long. (Shortest correctly formatted email address is a@a.aa)
• There must be exactly 1 "@" character.
• The "@" may not be the first character.
• At least 4 characters must follow the "@" character.
• There must be a period as either the third or fourth character from the end. (If there is more than one period in the address, this must be the last one.)
• There may be no consecutive periods.
• No period may be adjacent to the "@" character.
• There may be no commas.
If any of the above fail, CheckEmail() delivers an error message.
CheckName() uses IsItPresent() to see if anything has been typed into the form field. If not, an error message is delivered. Then it removes all but one of any consecutive spaces. Finally, it capitalizes the first letter of each name and makes everything else lower case.
ValidateAll() uses CheckEmail() and CheckName() to validate and correct the data in the related form input fields.
Other validation and correction functions will be added to the demonstration page from time to time. A function for URLs is already there, but not included in this article because of space considerations. Visit http://willmaster.com/possibilities/demo/formcheck.shtml to pick it up.
As other validation and correction functions are added to the page, they will be mentioned in the "Prelude" section of WillMaster Possibilities.
Have fun, and write to me if you need help.
Tutorial pages:
|
Copyright 2004 Bontrager Connection, LLC
|
|||||||||
You might also want to check these out:
|
Leave a Comment on "JavaScript Form Input Validation and Correction"
You must be logged in to post a comment.
Link to This Tutorial Page!

