HTML FORM Validation with JavaScript
Page Obsolete
- 2019-06-26 this page is outdated. Kept here for history purpose.
- 2025-04-24 basic form validation has been built in browser. see JS DOM: Email Field π§ and others.
This page shows you how to validate a HTML's FORM elements using JavaScript.
Example
Explanation
Here is the code for the form:
<form action="#" method="post" enctype="application/x-www-form-urlencoded" onSubmit="return(f(this));"> <p> Type A here: <input type="text" size="5" maxlength="5" name="fA">, Type B here: <input type="text" size="5" maxlength="5" name="fB">, <input type="submit"> </p> </form>
Notice the code <form action="#" β¦ >
. The #
just means the current page. In practice, the value should be a URL where this form is processed.
The most important code is this line onSubmit="return(f(this));"
. This means, when
user clicks the submit button, the function βfβ is called, and the
form itself is passed as argument.
In the above, each field is named like βfAβ, βfBβ. In the following JavaScript code, we have functions βf1β, βf2β to validate each field. βf1β is for validating field βfAβ, βf2β is for validating field βfBβ. This way, you can easily see how to extend the code if you have many more fields and needs different validation.
Here is the JavaScript code:
// function to validate a field function f1(x) { if (x.value=='A') {return true} else {return false}} // function to validate a field function f2(x) { if (x.value=='B') {return true} else {return false}} // function to validate whole form function f(x) { if (f1(x.fA)==false) {x.fA.focus(); alert("This should be A."); return false} if (f2(x.fB)==false) {x.fB.focus(); alert("This should be B.") return false} alert("Perfect! Form is Sent"); return true; }
Each f1 and f2 are functions that validate specific input field. If the input is valid, then f1 returns true, else false. Similar for f2.
The function βfβ calls each of the f1 and f2, for validating the whole form. When βfβ returns true, then the browser will submit the data. (to the server at the URL that is the value of βactionβ attribute in βformβ tag.)
The function βfβ has a single parameter named x. This is the HTML form object. In the HTML form code:
<form β¦ onSubmit="return(f(this));">
f receives the form object as its argument. Similarly, each f1, f2, takes a single parameter that should be the object of the field.
The x.fA
is the object of that field name fA.
You can use the dot notation to refer to values of the various input items. Therefore,
x.fA
is the object of the form field named fA, x.fA.value
is that field's value.
For validation that happens right away when user presses tab to go to next field, see: Instant Form Field Validation .