JS Validation - v2.3
Introduction
This script lets you add javascript validation to your forms quickly and with very little effort. The script checks the values that a user has entered into your webform, and if it doesn't meet the criteria specified (e.g. they failed to enter a value, or they entered a fake email address), a popup window appears with a custom message, the focus is placed on the offending field and the field is highlighted to indicate what field needs to be fixed.
To see a demonstration of all the different validation options, click here. This demo form contains all the validation options currently offered by the script. Version 2.2 (May 2007) includes some more advanced options such as regular expression and custom function support. Version 2.3 was just for a minor bug fix regarding the new function option.
Note: this script was designed to be identical to the PHP Validation code; both employ exactly the same logic, so you can simply copy and paste the validation rules from one to the other, providing both client- and server-side validation with very little work!
How to add add validation to your form
Okay, let's get started! Here are the steps you'll need to do to get it working with your form. We'll go into more detail in the later pages - this page is mainly just to give you a general sense of how it fits together.
- Download the javascript validation file (validation.js) then upload it to the same folder containing your webpage, and import the code in between your webpage's <head>...</head>, like so:
<script type='text/javascript' src='validation.js'></script>
- Add your form-specific validation code. This is basically a LIST (or an array for the technically-literate), saying which form fields need to validated, in what way, and what error message should pop up if they're not filled in properly. See the demo form and explanation section for an illustration of how these rules work. And see the validation rules section for some details about the format of the specific rules.
- Lastly, add an onSubmit handler to your form's <form> tag, like so:<form ... onSubmit='return validateFields(this, rules)'>
This tells the form to execute the validation script every time the user submits the form. Only when there are no errors is the form actually submitted.
Demo form and explanation
Probably the best way to understand how this works is to see an example. In the demonstration page, the form-specific validation code is as follows:
var rules = new Array(); // stores the validation rules // standard form fields rules.push("required,user_name,This field is required."); rules.push("required,email,Please enter your email address."); rules.push("valid_email,email,Please enter a valid email address."); // date fields rules.push("valid_date,any_date_month,any_date_day,any_date_year,any_date,Please enter a valid date."); rules.push("valid_date,later_date_month,later_date_day,later_date_year,later_date,Please enter an date later than today."); // Numbers / alphanumeric fields rules.push("required,any_integer,Please enter an integer."); rules.push("digits_only,any_integer,This field may only contain digits."); rules.push("digits_only,number_range,This field may only contain digits."); rules.push("range=1-100,number_range,Please enter a number between 1 and 100."); rules.push("range>100,number_range_greater_than,Please enter a number greater than 100."); rules.push("range>=100,number_range_greater_than_or_equal,Please enter a number greater than or equal to 100."); rules.push("range<100,number_range_less_than,Please enter a number less than 100."); rules.push("range<=100,number_range_less_than_or_equal,Please enter a number less than or equal to 100."); rules.push("letters_only,letter_field,Please only enter letters (a-Z) in this field."); rules.push("required,alpha_field,Please enter an alphanumeric (0-9 a-Z) string."); rules.push("is_alpha,alpha_field,Please only enter alphanumeric characters (0-9 a-Z) in this field."); rules.push("custom_alpha,custom_alpha_field1,LLL-VVV,Please enter a string of form LLL-VVV - where L is " + "an uppercase letter and V is an uppercase vowel."); rules.push("custom_alpha,custom_alpha_field2,DDxxx,Please enter a string of form DDxxx."); rules.push("custom_alpha,custom_alpha_field3,EEXX,Please enter a string of form EEXX."); rules.push("custom_alpha,custom_alpha_field4,VVvvllFF,Please enter a string of form VVvvllFF."); rules.push("custom_alpha,custom_alpha_field5,#XccccCCCC,Please enter a string of form #XccccCCCC."); rules.push("reg_exp,reg_exp_field1,^\s*(red|orange|yellow|green|blue|indigo|violet|pink|white)\s*$,Please " + "enter your favourite colour in lowercase (e.g. \"red\" or \"blue\")"); rules.push("required,reg_exp_field2,Please enter your favourite colour (e.g. \"red\" or \"blue\")"); rules.push("reg_exp,reg_exp_field2,^\s*(red|orange|yellow|green|blue|indigo|violet|pink|white)\s*$,i,Please " + "enter your favourite colour (e.g. \"red\" or \"blue\")"); // Length of field input rules.push("length=2,char_length,Please enter a value that is exactly two characters long."); rules.push("length=3-5,char_length_range,Please enter a value that is between 3 and 5 characters in length."); rules.push("length>5,char_length_greater_than,Please enter a value that is over 5 characters long."); rules.push("length>=5,char_length_greater_than_or_equal,Please enter a value that is at least 5 characters long."); rules.push("length<5,char_length_less_than,Please enter a value that is less than 5 characters long."); rules.push("length<=5,char_length_less_than_or_equal,Please enter a value that is less than or equal to 5 characters."); // custom functions rules.push("function,my_custom_function"); // password fields rules.push("required,password,Please enter a password."); rules.push("same_as,password,password_2,Please ensure the passwords you enter are the same."); // conditional (if-else) fields rules.push("required,gender,Please enter your gender."); rules.push("if:gender=male,required,male_question,Please enter the name of your favourite Care Bear."); rules.push("if:gender=female,required,female_question,Please indicate what max weight you can bench.");
Each rules.push("...") statement pushes (adds) a new validation requirement into the rules list. The push statements each contain a string (i.e. a bunch of characters wrapped in double quotes. The push statements are all of the following form:
Available validation rules
To recap: the validation rules are all of the following form:
if:FIELDNAME!=VALUE,
required | field must be filled in | ||||||||||||||||||||||||
digits_only | field must contain digits only | ||||||||||||||||||||||||
length=X | field has to be X characters long | ||||||||||||||||||||||||
length=X-Y | field has to be between X and Y (inclusive) characters long | ||||||||||||||||||||||||
length>X | field has to be greater than X characters long | ||||||||||||||||||||||||
length>=X | field has to be greater than or equal to X characters long | ||||||||||||||||||||||||
length<X | field has to be less than X characters long | ||||||||||||||||||||||||
length<=X | field has to be less than or equal to X characters long | ||||||||||||||||||||||||
valid_email | field has to be valid email address | ||||||||||||||||||||||||
valid_date | field has to be a valid date fieldname: MONTH field fieldname2: DAY field fieldname3: YEAR field date_flag: "later_date" / "any_date" |
||||||||||||||||||||||||
same_as | fieldname is the same as fieldname2 (for password comparison) | ||||||||||||||||||||||||
range=X-Y | field must be a number between the range of X and Y inclusive | ||||||||||||||||||||||||
range>X | field has to be a number greater than X | ||||||||||||||||||||||||
range>=X | field has to be a number greater than or equal to X | ||||||||||||||||||||||||
range<X | field has to be a number less than X | ||||||||||||||||||||||||
range<=X | field has to be a number less than or equal to X | ||||||||||||||||||||||||
is_alpha | field has to be an alphanumeric character (anything between 0-9, a-Z) | ||||||||||||||||||||||||
custom_alpha |
This option is a layman's version of the reg_exp rule and offers more control
than the letters_only rule. It lets you check that a field is formatted in a very
specific way. For example:
// this requires the "field_name" form field be of the form: {any letter}{uc letter}{lc consonant}{lc consonant} rules.push("custom_alpha,field_name,DLcc,Error message"); Here's all the different formatting options and what each character means:
Any characters included in the string that aren't in the above list are simply required as they are. So if your rules was CVC-VCV, the user would have to enter consonant, vowel, consonant followed by a dash, followed by vowel, consonant, vowel. |
||||||||||||||||||||||||
reg_exp |
This option is for programmers only. It lets you validate a field by a regular expression.
This rule comes in two forms: one with a RegExp flag (like "g" for global, "i" for
case-insensitive etc.) and one without. Unless you expressly need to supply a flag, just
use the first form.
Note: be sure to double-escape regexp escape characters. e.g. to match whitespace,
the \s needs to be \\s.
|
||||||||||||||||||||||||
letters_only | field has to be a letter, a-Z (upper or lowercase) |
||||||||||||||||||||||||
function |
This option is included for programmers. You may find that you need to supplement
the existing functionality with your own custom validation rules. Before version 2.2
you had to do some creative hacks to let this happen - or drop the script altogether.
Now you can embed your own custom functions directly within the other rules so that
the sequential execution of each rule will continue to function, and you can ensure your
custom validation occurs at the appropriate spot. The format of the rule is very simple:
rules.push("function,your_function_name");Then, you need to define your own javascript function your_function_name. This function cannot take any arguments. In order for your function to interact properly with the validation script, your function must to do two things:
Tip: use the built-in alertMessage() function to generate the popup error
message for your custom script. This function focuses on the offending field for you and
pops open the message. See the demonstration form
for an illustration of this.
From comparing this function rule with the other rules above, you'll notice a few things that are different:
|
Notes: With the digits_only, valid_email and custom_alpha rules, if the empty string is passed in it won't generate an error, thus allowing validation of non-required fields. So, if you want a field to be a valid email address, for example, provide separate rules for both "required" and "valid_email" for that single form field.
Other comments
JS vs. PHP Validation
As mentioned earlier, the PHP validation script was written to be identical to the JS Validation sister script, so you can just copy and paste the rules from one to the other. The only validation rule that doesn't appear in the PHP Validation is the function rule. Due to the way the JavaScript validation works - rule by rule, showing a single popup error at a time - the function rule was needed to let you leave the standard control flow execution and run your own function(s). With PHP, this isn't required: you can simply embed the custom scripts directly in the PHP code.
Download
Click the link below to download the script.
As always, if you encounter any bugs or have feature suggestions, please contact me.