1. Introduction
Using client side JavaScript is an efficient way to validate the user input
in web applications. When there are many fields in the form, the JavaScript
validation becomes too complex.
The JavaScript class presented here makes the form validations many times easier.
The idea is to create a set of "validation descriptors" associated with each element
in a form. The "validation descriptor" is nothing but a string specifying the type of
validation to be performed.
Each field in the form can have 0, 1, or more validations. For example, the input should
not be empty, should be less than 25 chars, should be alpha-numeric, etc
You can associate a set of validation descriptors for each input field in the form.
2. Steps
1.Call the gen_validatorv2.js in your html file just before closing the HEAD tag
NOTE: To test the script locally, make sure the gen_validatorv2.js file is in the same directory as your
test form, or change the path (src="") to it in the call below to match its location in relation to the form.
You must also upload the gen_validatorv2.js to your server insuring the call path in your forms (src="") is correct.
Make sure to upload the .js file as TEXT - not Binary.
<script language="JavaScript" src="gen_validatorv2.js" type="text/javascript"></script>
</head>
2. Just after defining your form,
Create a form validator object passing the name of the form
<FORM name='myform' action="">
<!----Your input fields go here -->
</FORM>
<SCRIPT language="JavaScript">
var frmvalidator = new Validator("myform"); >
....
3. Now add the validations required
frmvalidator.addValidation("FirstName","alpha","Only letters are allowed for a First Name");
the first argument ("FirstName" is this case) is the name of the field and the second argument ("alpha" in this case) is the
validation descriptor, which specifies the type of validation to be performed.
You can add any number of validations. The list of validation descriptors are provided
at the end of the documentation.
The optional third argument ("Only letters are allowed for a First Name" in the sample above) is the error string to be displayed if the validation
fails.
frmvalidator.addValidation("FirstName","alpha","Only letters are allowed for a First Name");
frmvalidator.addValidation("FirstName","req","Please enter your First Name");
frmvalidator.addValidation("FirstName","maxlen=20",
"Max length for FirstName is 20");
4. Similarly, add validations for the fields where validation is required.
Thats it! You are ready to go.
3. Example
The example below will make the idea clearer
<form action="" name="myform" >
<table cellspacing="2" cellpadding="2" border="0">
<tr>
<td align="right">First Name</td>
<td><input type="text" name="FirstName"></td>
</tr>
<tr>
<td align="right">Last Name</td>
<td><input type="text" name="LastName"></td>
</tr>
<tr>
<td align="right">EMail</td>
<td><input type="text" name="Email"></td>
</tr>
<tr>
<td align="right">Phone</td>
<td><input type="text" name="Phone"></td>
</tr>
<tr>
<td align="right">Address</td>
<td><textarea cols="20" rows="5" name="Address"></textarea></td>
</tr>
<tr>
<td align="right">Country</td>
<td>
<SELECT name="Country">
<option value="" selected>[choose yours]
<option value="008">Albania
<option value="012">Algeria
<option value="016">American Samoa
<option value="020">Andorra
<option value="024">Angola
<option value="660">Anguilla
<option value="010">Antarctica
<option value="028">Antigua And Barbuda
<option value="032">Argentina
<option value="051">Armenia
<option value="533">Aruba
</SELECT>
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
<script language="JavaScript" type="text/javascript">
var frmvalidator = new Validator("myform");
frmvalidator.addValidation("FirstName","req","Please enter your First Name");
frmvalidator.addValidation("FirstName","maxlen=20",
"Max length for FirstName is 20");
frmvalidator.addValidation("FirstName","alpha");
frmvalidator.addValidation("LastName","req");
frmvalidator.addValidation("LastName","maxlen=20");
frmvalidator.addValidation("Email","maxlen=50");
frmvalidator.addValidation("Email","req");
frmvalidator.addValidation("Email","email");
frmvalidator.addValidation("Phone","regexp=^[0-9\-\(\)\ \.]{10,14}$",
"Only numbers, spaces, dashes or ( ) are allowed for a phone number and the total for digits and spaces should be between 10 and 20 characters");
frmvalidator.addValidation("Address","maxlen=50");
frmvalidator.addValidation("Country","dontselect=0");
</script>
There is a table at the end of this document explaining the use of different validators such as alpha, numeric, maxlen and more.
However, a further explanation of regexp or regular expression is needed.
You will see this used for the field "Phone" above. One might think you could simply use the "numeric" validator - meaning only 0-9 could
be used. But, unless you have very specific instructions, a request for a phone number might be provided as any of the following: 1-303-334-5566 or (303) 334-5566 or 3033345566.
Only the last example - 3033345566 - would pass a numeric validation because numeric does not include spaces, dashes, or any special characters. The same goes
for an alpha validation which only include a-z and A-Z - no spaces, dashes, periods or anything except letters.
Therefore, if you use a field such as "Your Full Name", you could not use an alpha validation because the full name of - Joe T. Smith - contains both
spaces and a period. In this case, you want to use a "regexp" to define EXACTLY what can be used.
Let's examine the sample from "Phone" above: "regexp=^[0-9\-\(\)\ \.]{10,14}$"
The "regexp=^ and the ending $" will be constant - they are always used. It is what is within the first set of brackets [ ] that determines
what characters are acceptable. In this sample, that would be the 0-9, the dash, ( or ), a space and the period. That's it, nothing else
will be accepted for this field - but it does allow the user to provide a phone number in the standard methods of using either/or dashes or ().
So, what are all the "\" backslashes within the "regexp=^[0-9\-\(\)\ \.]{10,14}$"? In this type of script, the 0-9a-zA-Z are accepted at face value -
meaning everything letter between the a and the z and such. However, many special characters, such as the dash, * and more have command functions
within the script. Therefore, the backslash is used as an escape character - telling the script to treat what follows at face value - not as a
possible command function. So, it is necessary to proceed anything other than 0-9a-zA-Z with the escape \.
Now, you may also optionally define the minimum and maximum number of characters allowed within a regexp. You will see this in the example
as {10,14} - meaning 10 as a minimum and 14 as a maximum number of characters. If you ask for an area code and phone number, 10 is the absolute minimum
numbers of characters needed - such as 3033345566. Where as 1-303-334-5566 is 14 characters. Any more or less characters is probably an invalid phone number.
For the "Your Full Name" field, you would use something like "regexp=^[a-zA-Z\ \.]{10,50}$". Meaning all letters (lowercase and uppercase), the space and the period are allowed
and the minimum numbers of characters is 10 and the maximum is 50. It doesn't take long to figure out how to use this type of validation to really
fine tune what you accept for any given field on your form.
4. Things to remember
The form validators should be created only after defining the HTML form
(only after the </form> tag. )
Your form should have a distinguished name.
If there are more than one form
in the same page, you can add validators for each of them. The names of the
forms and the validators should not clash.
You can't use the javascript onsubmit
event of the form if it you are using this validator script. It is because
the validator script automatically overrides the onsubmit event. If you
want to add a custom validation, see the section below
5. Adding Custom Validation
If you want to add a custom validation, which is not provided by the validation descriptors,
you can do so. Here are the steps:
Create a javascript function which returns true or false depending on the validation.
>
function DoCustomValidation() >
{
var frm = document.forms["myform"];
if(frm.pwd1.value != frm.pwd2.value)
{
alert('The Password and verified password don not match!');
return false;
}
else
{
return true;
}
}
Associate the validation function with the validator object.
frmvalidator.setAddnlValidationFunction("DoCustomValidation");
The custom validation function will be called automatically after other validations.
6. Clear All Validations
In some dynamically programmed pages, it may be required to change the validations in the
form at run time. For such cases, a function is included which clears all validations in the
validator object.
frmvalidator.clearAllValidations();
this function call clears all validations you set.
You will not need this method in most cases.
7. Table of Validation Descriptors
required
req
|
The field should not be
empty
|
maxlen=???
maxlength=???
|
checks the length entered data to the maximum.
For example, if the maximum size permitted is 25, give the
validation descriptor as "maxlen=25"
|
minlen=???
minlength=???
|
checks the length of the entered string to the
required minimum. example "minlen=5"
|
alphanumeric /
alnum
|
Check the data if it
contains any other characters other than alphabetic or numeric characters
|
num
numeric
|
Check numeric data
|
alpha
alphabetic
|
Check alphabetic data.
|
| email
|
The field is an email
field and verify the validity of the data.
|
lt=???
lessthan=???
|
Verify the data to be less than the value passed.
Valid only for numeric fields.
example: if the value should be less than 1000
give validation description as "lt=1000"
|
gt=???
greaterthan=???
|
Verify the data to be greater than the value passed.
Valid only for numeric fields.
example: if the value should be greater than 10
give validation description as "gt=10"
|
| regexp=???
|
Check with a regular expression the value should match the regular expression.
example: "regexp=^[A-Za-z]{1,20}$" allow up to
20 alphabetic characters.
|
| dontselect=??
|
This validation descriptor is valid only for
select input items (lists) Normally, the select list boxes will have
one item saying 'Select One' or some thing like that. The user
should select an option other than this option. If the index of this
option is 0, the validation description should be "dontselect=0"
|
8. Example Page
See the example Page here
|