HTML FORM Validation with JavaScript

By Xah Lee. Date: . Last updated: .

2019-06-26 this page is outdated. Kept here for history purpose.

This page shows you how to validate a HTML's FORM elements using JavaScript.


Type A here: , Type B here: ,


Here is the code for the form:

<form action="#" method="post"
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">

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:


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 .

JavaScript in Depth