When you create a form, you often will want to check the values people enter into the form. For example, you might want to require first name, last name, and a valid email address. Checking these values before a form is sent to the server is called "Form Validation".
There are a number of ways to do this, but one of the easiest and most flexible is to use Javascript. Some of this may seema little complicated, but it's really not too bad, and you can cut and paste from the examples.
Our reference source will be our friends at w3schools. It is worth taking the time to go through all of their tutorials on Javascript.
In particular you may wish to look at: http://www.w3schools.com/js/js_form_validation.asp
In order to validate a form entry, the first thing you need to do is to name the various blanks in your form. Dom is the formal name for the system of object names used in web pages. You don't really need to know a lot about it to make this work but some afternoon you might want to google the subject. For now let's just say that objects can have names specified by the "name" option in the html tag.
Let's create a blank for a name. Here's the html:
Name: <input type="text" name="fname">
Here's what it looks like on the page:
First name:
This of course has to be inserted into a complete form. So here's that form:
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
This is just our standard form as we have done before, excepting that we have added a couple of commands to the <form name....> html tag. There is a reference to "demo_form.asp" which is the handler for the form. In our previous example we had a different handler that forwarded the form via email. We won't be worrying about this much, because we're looking at validating the form BEFORE it is sent anywhere.
Next we have the command
onsubmit="return validateForm()"
This is the part that calls the validator. We have not created the validator yet, so that's next:
<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["fname"].value
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
The line that starts with "var x" takes the value from the form field called "fname" and puts it in the variable "x". Then we do a couple of tests, to see if X is null or a character string of length zero. Either one basically means no answer. If the test fails, an alert box pops up, and "false" is returned, which has the effect of rejecting the form back to the user to complete. Nothing is submitted to the server.
Here is the complete page:
<html>
<head>
<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["fname"].value
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
</head><body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body></html>
You can take this incantation and copy it and modify it. You can put in new fields with new names and do the same tests pretty easily
Create a form that asks for first name and last name and then checks to see that they are not null and not zero length strings. Should be pretty easy.
Here's a test to check a form field for an email address:
function validateForm()
{
var x=document.forms["myForm"]["email"].value
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
Basically this test looks for the "@" and "." characters and makes sure they are in reasonable locations in the email. Of course it still could be invalid but at least there will be some kind of reasonable looking answer.
"||" means or. So the if condition is if the at position <1 or dot position < atpos+2 or etc. etc. etc.
Do the first test. If it fails, return with fail and set the focus to the failed element.
If the first test works, don't return yet, just go to the next test, by adding it in sequence.
At the end, if every test is true, then return true, but only then.
If you return too early in the script, then you don't get a chance to try all the tests.
Click here to see the example, then view source to see how it works.
Excercise: add an email field to your form and add validation.
A script to test for zero length. Note the use of the "focus" command that puts the cursor into the form with the error. This makes it easy for the user to find the spot with the error.
"Elem" is the name of the field we want to test. Look at the first example to see how to spell this out exactly.
elem=document.forms["myForm"]["email"]
You can fill in the right names for your form fields.
if(elem.value.length == 0){
alert("Your entry is zero length, please try again.");
elem.focus(); // set the focus to this input
return false;
}
return true;
A script to test for all numbers, also with the focus command.
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){
return true;
}else{
alert("Numbers only please");
elem.focus();
return false;
}
A script to check for all letters:
var alphaExp = /^[a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert("Letters only please");
elem.focus();
return false;
}
Here's one that limits minimum and maximum length of the field:
var uInput = elem.value;
var min=3;
var max=8;
if(uInput.length >= min && uInput.length <= max){
return true;
}else{
alert("Please enter between " +min+ " and " +max+ " characters");
elem.focus();
return false;
}
Note that if you do the test the way they are shown above, all of the tests go against the same field, "elem".
Create a form that gets a first name, last name, an email, a phone number, and a credit card number with expiration date. Make sure that the user puts reasonable values in every blanks and use alert boxes to tell the user what they need to do.