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:
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:
- You will almost certainly need to name your form in order to be able to access the data elements inside it.
- The "
onsubmit
" handler need to necessarily validate the data - it could do some pre-processing instead.