Validating a Form
Question:
How do I validate the form input before sending it to the server?
Answer:
To validate the form input, call your validation function from the form's
onSubmit event handler.
When the user submits the form, the browser will first invoke
the onSubmit event handler.
The form will actually be submitted to the server only
if the handler returns true .
In the following example, the onSubmit
event handler validates the user's email address.
(For simplicity, the address is considered to be valid
if it does not contain spaces, contains the @ character
and if @ is neither the first nor the last character.)
This example used the following code:
<script language="JavaScript">
<!--
function isValid() {
var email=document.form1.t1.value;
if (email.indexOf(' ')==-1
&& 0<email.indexOf('@')
&& email.indexOf('@')+1 < email.length
) return true;
else alert ('Invalid email address!')
return false;
}
//-->
</script>
<form name=form1
action="javascript:alert('The form is submitted.')"
onSubmit="return isValid()">
Your email:
<input type=text name=t1 size=20 >
<input type=submit value=Submit>
</form>
Back
|