Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q157 Is there a way for me to validate a form BEFORE submit so it will never arrive at the page?

You are here: irt.org | FAQ | JavaScript | Form | 5 | Q157 [ previous next ]

You use the forms onSubmit event handler to trap the form submission, which you can redirect to perform form validation, and, if everthing if okay, allow the form submission to go ahead, else you cancel it:

<SCRIPT LANGUAGE="JavaScript"><!--
function myFunction() {
    var failed = false;
    // stick some form field validation in here
    if (failed)
        return false;
    else
        return true;
}
//--></SCRIPT>

<FORM NAME="myForm" onSubmit="return myFunction()">
<!-- put some form fields in here -->
<INPUT NAME="myButton" TYPE="SUBMIT">
</FORM>

It is also possible to submit a form using submit():

document.myForm.submit();

However in this instance the onSubmit event handler is *NOT* invoked. Also it'll not work if the action is 'mailto:'

Another way to submit a form is to use click:

document.myForm.myButton.click();

However this then does not invoke the onClick event handler of the button in anything less than Netscape Navigator 4 or Internet Explorer 4.

As the following example will demonstrate:

<FORM NAME="myForm">
<INPUT TYPE="BUTTON" NAME="myButton" onClick="alert('Hello World')" VALUE="Click Me">
</FORM>

<FORM>
<INPUT TYPE="BUTTON" onClick="document.myForm.myButton.click()" VALUE="Click Me">
</FORM>

©2018 Martin Webb