This small but powerful script lets you add javascript validation to your forms quickly and with very little effort. No programming experience is necessary, but it’s fully extensible to allow programmers to augment the built-in validation rules with their own.
Contents
- Features
- Getting Started
- Available Validation Rules
- Configuration Options
- Custom Validation Rules
- Demo forms
- Other Comments
- Download
Features
RSV comes with a number of validation rules for the more common tasks, including:
- Checking required fields
- Email validation
- Checking input field lengths: exact minimum or maximum lengths
- Date validation
- Integers: checking ranges, in between, greater than, less than
- Regular Expressions or “custom alpha” (layman’s regexps)
- Alphanumeric or letters only
- Nested conditional testing (if field A == something, then validate field B)
But also, the script is fully extensible to allow you to write your own custom validation routines to be integrated with the script.
The configuration options include:
- The choice of displaying the errors to the user sequentially (a single alert box showing the first error, which re-appears whenever the user resubmits the form), all at once (an single alert box containing all errors) or by displaying the errors as HTML in the page, via DHTML.
- An option to highlight (via a custom CSS class) all offending fields and auto-focus on the first field for ease of use.
- For advanced users, there is the option of passing all error information to a custom function to manage the errors as you see fit.
- Also for advanced users is the option to define a custom onComplete function which gets called when the form validation is successful.
To see a demonstration of various configuration patterns, take a look at the demo pages.
Getting Started
Okay, let’s get started! To my mind, the quickest way to learn how to implement this script is to take a look at the demo forms. Personally, I always learn much quicker from viewing examples. But for those of a different stripe, here’s some step by step instructions.
-
First, download the compressed javascript validation file from github and upload it to the same folder containing your webpage. Import the code in between your webpage’s <head>…</head>, like so:
1<script src="rsv.js"></script>Note: You can either use the compressed or uncompressed version (rsv-uncompressed.js). But unless you’re planning on modifying the code, I would suggest using the compressed version since it’s smaller for browsers to download.
-
Add your form-specific validation code. This is basically a LIST (or an array for the technically-literate), saying which form fields need to be validated, in what way, and what error message should be displayed to the user if they’re not filled in properly. Here is a simple example:
1
2
3
4var rules = []; // this stores all the validation rules
rules.push("required,first_name,Please enter your first name.");
rules.push("required,email,Please enter your email address.");
rules.push("valid_email,email,Please enter a valid email address.");Here we are checking that the first name and email fields have a value, and that the email address is valid. Each rules.push(“…”) line adds a new validation rule to the list. The “push” statements each contain a string (i.e. a bunch of characters wrapped in quotes. The push statements are all of the following form:
1"[if:FIELDNAME=VALUE,]REQUIREMENT,fieldname[,fieldname2[,fieldname3,date_flag]],error message"The square bracket [] notation indicates that the contents are optional, depending on the REQUIREMENT rule used by the line. Note: if you need to include commas in the error messages you must escape them with two double-slashes, like so: \\,
-
Lastly, add an onsubmit handler to your form’s <form> tag, like so:
1<form ... onsubmit="return rsv.validate(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.
Note: A more elegant approach would be to attach the onsubmit event via a bootstrap function (included in all modern JS frameworks like Prototype, jQuery, Dojo, MooTools etc),
but this is outside the scope of this doc.
Available Validation Rules
To recap, validation rules are strings of the following form:
1 | "[if:FIELDNAME=VALUE,]REQUIREMENT,fieldname[,fieldname2[,fieldname3,date_flag]],error message" |
The square bracket [] notation indicates that the contents are optional. Note: if you need to include
commas in your error messages, you must prefix them (“escape” them) with two backslashes like so: \\, otherwise your error message will appear truncated.
if:FIELDNAME!=VALUE,
This allows us to only validate a field only if a fieldname has – or doesn’t have –
a particular value. This option allows for nesting; i.e. you can have multiple if clauses, separated
by commas. They will be examined in the order in which they appear in the line.
Valid REQUIREMENT strings are:
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 |
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: |
1 2 | // 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. 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 format. |
1 2 3 4 5 | // Format 1: rules.push("reg_exp,field_name,REGEXP,Error message"); // Format 2 rules.push("reg_exp,field_name,REGEXP,Flag(s),Error message"); |
Note: be sure to double-escape regexp escape characters. e.g. to match whitespace,
the \s needs to be \\s; commas also need to be double escaped: \\, |
|
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. See the page on custom functions for more information about this rule. |
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 both required AND a valid email address, provide separate rules for both “required” and “valid_email” for that single form field.
Configuration Options
At the top of the rsv.js file, you will find the following lines where you may customize your script. You have the choice of either editing these configuration options directly in the validation script file, or adding them to your page, overriding them there. So if you need the validation to function differently in two different pages, redefining these values in your page is a better way to go (since the user then won’t have to download two copies of the script!)
1 2 3 4 5 6 7 8 9 | // SETTINGS rsv.displayType = "alert-all"; // "alert-one", "alert-all" or "display-html" rsv.errorFieldClass = null; rsv.errorTextIntro = "Please fix the following error(s) and resubmit:"; rsv.errorJSItemBullet = "* "; rsv.errorHTMLItemBullet = "• "; rsv.errorTargetElementId = "rsvErrors"; rsv.customErrorHandler = null; rsv.onCompleteHandler = null; |
Custom Validation Rules
Even though the built in validation rules are pretty generic, there’s always going to be a situation where you need to do some custom validation. Before version 2.2 you had to do some creative hacks to let this happen, but 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 and is displayed at the appropriate spot. The format of the rule is very simple:
1 | rules.push("function,your_function_name"); |
Then, you need to define your own javascript function your_function_name. This function cannot take any arguments.
From comparing this function rule with the other built-in validation rules, you’ll notice a few things that are different:
- There’s no mention of a particular field in the rule. This is deliberate. Since I really have no idea what validation you plan on adding, it may be using multiple fields so there was no point passing along a single value. You will need to directly access the field values themselves within your custom function.
- The function name doesn’t have a “()” following it. Don’t add it; it’s added by the code.
In order for your function to interact properly with the RSV script, your function must have a well-defined return value. Namely:
- If the field passes whatever test or tests you administer, it must explicitly return true.
- If it fails the test(s), it has to return an array of arrays, like so:
1 | return [[node1, "error message1"], [node2, "error message2"], [node3, "error message3"]]; |
Or if your function is just throwing a single error:
1 | return [[node, "error message"]]; |
Note the double [[ and ]]. That’s a not a typo!
An example
Here’s a simple example from one of the demo forms. It checks to see if a field is a prime number under 100 and if it fails, returns the error message which will be displayed by the RSV script according to the config options specified.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | function my_custom_function() { var prime_nums_str = "1|2|3|5|7|11|13|17|19|23|29|31|37|41|43|47|53|59|61|67|71|73|79|83|89|97"; var prime_numbers = prime_nums_str.split("|"); var val = document.getElementById("prime_number").value; var is_valid_num = false; for (i=0; i<prime_numbers.length; i++) { if (prime_numbers[i] == val) { is_valid_num = true; } } if (!is_valid_num) { var field = document.getElementById("prime_number"); return [[field, "Please enter a prime number under 100"]]; // returns a single error message } return true; } |
Demo Forms
There’s no better way to help you better understand the script its functionality by seeing it in action. So here are a few demo forms that highlight the various configuration options, build in validation rules, custom rules and examples of how to extend the script.
Other Comments
JS vs. PHP Validation
This script was written to be identical to the PHP Validation sister script, so you can just copy and paste the rules from one to the other. If you’re a PHP programmer, you may want to take a look at it!
Download
This script is found here on github. Just download the standalone script from there.