Form Validator R3.0

Jake Howlett, 6 June 2006

Category: Forms; Keywords: validation prototype fields

Forms are as much a part of the web now as are normal text pages, often created by these forms.... expand!

Using The Code 

Using the code is simple. That's the whole idea behind it. You don't really need any JavaScript knowledge to be able to use the approach described here, although it might help in understanding how the list of required fields is compiled.

First thing you need to do is copy the required JavaScript Libraries/files to your database. These are prototype.js and effects.js, which are stored as Files in the example database, along with global.js and validation.js, which are stored in Script Library objects.

Once these are there you need to import them in the form to be validated's header. See the form called Contact in the example database to see how.

Now we need to setup the form to use the Validator object. To do this we initialise it when the page loads, by calling the init() method in the onload event, by adding code like this to the Form's HTML Body Attributes:

"onload=\"Validator.init( '_Contact', 'beforeForm')\""; "") 

We pass two arguments to the init method. The first is the name of the form we're validating. In most cases this is simply the actual name of your Form preceded with an underscrore. If you're not sure of the name or you know it's the only form on the page you can simply pass 0 as this paramater, like so: 

"onload=\"Validator.init( 0 , 'beforeForm')\""; "") 

The second paramater passed is the ID of the object on the page after which you want to insert the message that validation has failed.

In the image above the message has been inserted after the two buttons, which are in a P with the id "beforeForm".

In the onsubmit event of the Form you need to tell it to call the validate() method and return the result (true/false) to the calling object.

return Validator.validate()

You now have all you need to run validation on your form. All you need to do is tell the Validator which field need validating. To do this you build an array called "fields" and add it to the Validator object. To create an the array which belongs to the Validator is as simple as this:


The array is empty though and not much use. We need to add something to it. Here's how we'd tell it to validate two fields:

{name: "FirstName"},
{name: "LastName"}

This is about as basic as it gets. When the Validator's validate() method is called it loops through each member of the fields array and tests their values. In this case it simply checks if either of the two fields are blank. If they are the default message "This field is required" is shown next to the field. If you don't want this message you can override for any particualy field like this

{name: "FirstName"},
{name: "LastName", message: "Come on, don't be shy!"}

Each entry in the fields array contained within the {} brackets is known as an associative array, to which we pass a set of key:value pairs. The only pair required is the field name. Other are optional and are listed here:

nameStringName of the field that you want to validate. This is the name of the actual field on the form, rather than its label, and is case-sensitive. Required.
What kind of field it is. Used mainly with plain text fields. Whethers it a dropdown, checkbox or radiobutton etc can be worked out automatically by the script.
messageString objectIf you're not happy with the default message you can supply your own.
JavaScript expression
Use this to only validate the field under certain conditions. The expression should return true of false. If true the field gets validation and vice-versa.
patternRegExp objectUsed with regex type fields.
Number or Date objectUsed with date/number type fields.
expressionJavaScript expressionFor use with custom field types. The expression should be the name of a function to call. This function can do whatever you like as long as it return eithers true or false. True if the field validates and false if not.
testFunction objectIf you supply this paramater then the Validator uses this function to validate the field instead of its own logic.


Advanced options: 

Here's how some of the other fields from the Contact demo form are setup for validation. Note the different combination of options used for each one.

Here we add a field that needs a valid email address entered. 

{name: "email", type: "email"} 

In the above field we should probably have added a custom message to alert the user to the fact this field must be a valid address. Otherwise there may be confusion. Like in the following field, where we require a certain format for a phone number, so we specify this in the error message to help the user. We specify the format by making the field a regex type and passing it a pattern to match, as shown: 

: "Phone",
type: "regex",
pattern: /^\+\s\d{2}\s\d{3}\s\d{4}$/,
message: "Please enter a phone number in the format \"+ 12 345 6789\""

Here's how to add a number field. In this case it's part of the address and is the house number. This is probably not a good example as there's no real reason the house number needs to be a number or why there'd be a minimum value of 55. Note we've missed out the max paramater and so there is none. Equally we could have a max and no min or no restraints at all. 

{name: "house", type: "number", min: 55}

The field call dob is a date field for the contact's date of birth. Here we pass it both a min and max setting, both of which are JavaScript Date objects. In this case the date of birth must be somewhere between the turn of last century and today. As well as being in a valid date format (dictated by Validator.DateFormat) of course.

: "dob",
type: "date",
min: new Date(1900, 1, 1),
max: new Date(),
message: "Please enter a valid and realistic date of birth"

Here's a conditional field. The Validator is told to only validate the field "kLevel" if the field called "cType" has the third option selected ("Developer").

name: "kLevel",
condition: "this.form.cType.selectedIndex==2",
message: "If you\'re a developer, please tell us what knowledge level"

Here's a custom validation. The expression value results in a call to a function which we write ourselves. In this case we pass the value of the field being validated to the function. It's then down to that function to return either true or false based on whatever logic is required. 

: "confirm",
type: "custom",
expression: "myExampleValidationFunction(this.form.confirm.value)",
message: "Please enter the text you see to the right of this field."

Note that the field called "confirm" is validated by a custom function completely separate to validation.js and called myExampleValidationFunction(), which we pass the value of the field itself.

We don't have to write a separate function though if we want a custom validation routine. We can pass custom logic straight to the Validator like this:

 name: "salary",
 test: function(fld) { return !(fld.value % 2) }, 
 message: "This must be an even number."

Don't ask me what salary would need to be an even number. It's just an example. This method is handy if the function is short and sweet. No point storing it elsewhere and cluttering your code up.

Note: We can still add extra fields even after we've created the array! Like this:

Validator.fields.push({name: "WoopsForgotThisOne"})

Other example include: to come.


Future enhancements:

Trying to design a validation routine to meet all requirement is not easy. blah.

Form Validator V2 (link) had the option to validate file upload extension types. Worth adding back in?

More to come....