www.cryer.co.uk
Brian Cryer's Web Resources

How to validate a form before submitting it

The contents of a form can be validated (i.e. checked or vetted) before being submitted by adding an "onsubmit" event handler to the form. By way of example, consider the following form:

OK to submit?

The HTML for the form is simply:

<form name="exampleForm" onsubmit="return Validate()">
<p><input type="checkbox" name="chkBox" value="ON">OK to submit?</p>
<p><input type="submit" name="B1" value="Submit"></p>
</form>

The "onsubmit" event handler is called before the form is submitted and the form is only submitted if the handler returns "true". If the handler returns "false" then this prevents the form from being submitted. In this example the onsubmit handler calls a JavaScript function called "Validate", defined below:

function Validate()
{
    if (document.exampleForm.chkBox.checked)
        return true;
    alert('You must check the box before submitting this form');
    return false;
}

This function should be replaced to perform whatever validation logic is required, remembering that it must return true or false.

Note: