For many this is the classic use for Javascript, form validation. As many programmers know, "don't trust users".
If you want the user to input their age you may assume that they will use a number, but there will be at least one who tries to type it in.
With this act they manage to crash the program dealing with the form input. So to guard against this we can use Javascript to help validate
the input before it is sent.
The advantage to this is that it is done client-side, at the users machine. This means that no extra time is wasted having to send the form
to the server, check it, and if required back to the user because they have made a mistake. The disadvantage is that the user has the ability
turn Javascript off, so remember it still pays to validate any input server-side before it is processed.
Create Form
The first task we have to do is to construct the actual form. The important aspect not to forget is the inclusion
of the name attribute. Without this performing validation using Javascript would be difficult.
<textarea name="chat" rows=5 cols=20></textarea>
For a copy of just the form click here.
Add Validation
Check if empty
This example is just going to show you some basic validation. The first check we make is to ensure that
the user has completed all the fields. We perform this in two parts; with the name fields we check if any text
has been entered, if not we assign a name for them.
/* check if first name option empty, call function
noValue passing the element in DOM notation*/
// where q = form name
// where qc = textarea name
function checkFormSubmit()
{
if ( noValue(q.firstName.value) )
{
// display message to textbox
qc.value += "What no first name? - I shall call you Bill\n";
// assign name to element
q.firstName.value = "Bill";
}
}
// function to check if any content
function noValue(val)
{
// javascript uses the regular expressions from perl
// Sebesta 4.12.1
if (val.search(/\w/) == -1)
// \w switch matches any char/int
{
// this fufils logic in checkFormSubmit call
return true;
}
return false;
} //noValue
Beware of the reverse logic. noValue is testing if empty, therefore returns true if empty.
This then executes the code inside of the selection statement of checkFormSubmit.
We repeat this for the last name.
The other check we perform is to just test if the elements have been entered by the user. This is somewhat
unnecessary as questions 2,3, and 4 have an initial selection coded into them.
We check the other elements by iterating over them each in turn, again using the DOM notation.
// where q = form name
// where qc = textarea name
function checkText(q, qc)
{
//Warn if text boxes are empty (alphanumeric is OK)
//qc.value += "checkText\n";
for ( var i =0 ; i < q.length; i++)
{
// calls noValue function (again)
if (noValue(q.elements[i].value))
{
qc.value += "No value: "+ q.elements[i].name + "\n";
}
}
}
Check age
The other field we want to check is that of age. The checks we want to perform here is that it is a numeric character
and that it is in an acceptable range. The range we are going to use for this is between 10 and 99.
The best way to perform this is by using regular expressions (also known as regex's).
Regexs are pattern matching, they
can be used to in a variety of ways. We are going to use them to check if a pattern can be matched (the age range).
The syntax for Javascript regex is similar to those of Perl (as this is where they stem from).
if (!q.age.value.match(/^[1-9][0-9]$/))
{
myAlert2(" Age between 10 and 99");
qc.value += "Age between 10 and 99\nAge is not in numbers.\n";
return false;
}
The function above executes if the regex is false (note the not symbol !),
and if it is runs the myAlert function that displays an alert pop-up box.
The actual regex breaks down like this;
- ^[1-9] - checks that the first character (specified by the ^) is in the range 1 to 9
- [0-9]$ - checks that the last character (specified by the $) is in the range 0 to 9
By specifying the first and last characters we are saying that they both must exist.
This eliminates single inputs (and therefore age below 10) and three digit inputs (ages over 99).
Using [0-9] as our regex wouldn't work. This would only check is any of the characters was a number.
This would allow an input of thr3e, as it contains a number in the range.
Process Form
Now we have our completed validation script we can apply it to the form. We do this by adding an event trigger in the
opening <form> tag.
onSubmit="return checkFormSubmit();
Now when the user clicks on the submit button it will evoke the script. If all goes well the script will return true and it will
be sent as per the action attribute. In this case the form submits to itself (remember
unit 3 - PHP) where it processes the fields
and displays them.
See a working example. of this script.
Source code of html page is here.
Back to top