Form Validation

Now you can access the contents of forms using javascript we can examine some Validation techniques.

This is an important application of javascript as it allows the client to check the data before it is sent out over the Internet.

Often the validation technique depends on what your trying to validate.

For example, to be valid an email address in a text box must possess has a specific set of characteristics.

Here is a site with a useful set of Form Validation techniques, www.echoecho.com/jsforms.htm.

You should now be able to understand and adjust them to match your requirements.

Apart from testing individual form elements we can also ensure that all the form elements on a page have been filled in.

Validating Form

View its source and study the code.

How the javascript validation works

The form uses the legalemail() function to check that a legal email address has been added using an onchange event. If the email address is faulty it highlights the faulty field.

The testform() function checks that all entries in the form have been filled out.
When the Submit button is pressed the onSubmit event causes the javascript function testform() to execute.
Only if the function testform() returns true is the data is sent to the server.
If there are any blank fields, an alert box is displayed and the function testform() returns false so no data is sent to the Web server.

Exercise
Build a page with a form which asks for your

Ensure that both boxes are completed and that the age is a number before allowing the data to be transferred over the web.

Hint: Validating Numbers