In several other tutorials, we have looked at various functions to check aspects of
form validation :
Here we are going to bring these all together, by writing a ValidateForm function that can
call these, or other similar functions.
You can then adapt this script to validate the particular fields you need in the way you require.
Ammend your <form> tag, so it looks something like this:
<form name=form1 action=address.asp method=post onsubmit="javascript:return ValidateForm(this)">
|
|
|
What the onsubmit method does here is waits for the results of the ValidateForm function.
If it returns true, our validation has succeeded - the form entries are in an acceptable form.
If it returns false, there has been an error, and the user will need to correct it before being allowed
to submit the form.
So now let's have a look at the ValidateForm function itself. Exactly how it will look of course will
depend on the fields you need to validate.
function ValidateForm(form)
{
if(IsEmpty(form.account_number))
{
alert('You have not entered an account number')
form.account_number.focus();
return false;
}
if (!IsNumeric(form.account_number.value))
{
alert('Please enter only numbers or decimal points in the account field')
form.account_number.focus();
return false;
}
return true;
}
|
|
|
To understand this function, remember that the return statement exits from the function and returns the code to the calling statement.
Therefore, if the field 'IsEmpty', we alert the user, set the focus of the form to the appropriate field, and return false as the result.
The calling statement reads the false value and does not submit the form. The user remains on the same page, with the focus pointing them
to the error of their ways.
If however all the checks are verified, at the end of the ValidateForm function, we have a return true statement, meaning the form will submit
successfully.
|
Useful Links

|
|