JavaScript Form Validating Tips, Code and Examples

This JavaScript article tutorial focuses on guiding you how to use plain-JavaScript to check input data of form elements. This JavaScript tutorial shows you step by step instructions to check the string form inputs, the numeric form user input; how to parse and check data inputs in form input elements, form textarea elements, form checkbox elements and form radio elements. Please go to the main section for full completed guides and JavaScript source code examples.

Read more other JavaScript article tutorials from same author:
- Credit Card Numbers JavaScript Validating Tips and Codes
- Design Better HTML5 Form Element Validator
- JavaScript Date and Time Validating Tutorials

Sampled by ©

Validating form input with JavaScript is easy to do and can save a lot of unnecessary calls to the server as all processing is handled by the web browser. It can prevent people from leaving fields blank, from entering too little or too much or from using invalid characters.

For an alternative approach to client-side form validation, without JavaScript, check out our new article on HTML5 Form Validation which is available now in most modern browsers.

Note: When the form input is important, it must always be checked or re-checked by using a server-side script. Otherwise a browser with JavaScript disabled, or a hacker trying to compromise your site, can easily submit invalid data.

Restricting input to alphanumeric characters

In the following example, the single input box, named input, must: a) not be empty; and b) contain only alphanumeric characters and spaces. Only if both tests are passed can the form be submitted.

<script type="text/javascript">
  function checkForm(form)
    // validation fails if the input is blank
    if(form.inputfield.value == '') {
      alert("Error: Input is empty!");

      return false;

    // regular expression to match only alphanumeric characters and spaces
    var re = /^[\w ]+$/;
    // validation fails if the input doesn't match our regular expression
    if(!re.test(form.inputfield.value)) {
      alert("Error: Input contains invalid characters!");
      return false;
    // validation was successful
    return true;


Note: The pre-defined class \w represents any alphanumeric character as well as the '_' character.

The regular expression ^[\w ]+$ will fail if the input is empty as it requires at least one character (because we used + instead of *). The first test in the example is therefore only necessary in order to provide a different error message when the input is blank.

The purpose of a form validation script is to return a boolean value (true or false) to the onSubmit event handler. A value of true means that form will be submitted while a false value will block the form from being submitting. The focus() command is used to set the focus to the problem element.

You can test the above script with different input values using this form:


The form is put together as follows:

<form method="POST" action="action" onSubmit="return checkForm(this);">
Input: <input type="text" size="32" name="input"> <input type="submit">


The name attribute of the input field is used to reference that field from within the checkForm function. With the advent of DHTML it's tempting to use id's to reference form fields, but that can lead to namespace conflicts and why make things more complicated than necessary.

When the form is submitted - either by hitting Enter or clicking on the Submit button - the onSubmit handler is triggered. This then calls our checkForm() function, passing a reference to itself (the form) as the only variable. This makes the value of the input box available within the function as form.input.value (the 'value' of the field called 'input' belonging to the form). Other form values are available using a similar syntax, although this becomes more complicated if you're using SELECT lists, checkboxes or radio buttons (see below for examples).

The checkForm function tests the form input against our conditions, returning a value of true if the form is to be submitted (when all tests have been passed) or false to abort (cancel) the form submission. It's that simple.

In a real-life situation you will most likely have more fields to check, and more complicated conditions, but the principle remains the same. All you need to do is extend the checkForm function to encompass the new fields and conditions:

  function checkForm(form)
    if(!condition1) {
       alert("Error: error message");
       return false;
    if(!condition2) {
       alert("Error: error message");
       return false;
    return true;

When a return command is encountered, execution of the function is halted. In other words if the first condition fails, the second condition will not be tested and so forth. Only when all conditions have been satisfied do we reach the return true command, in which case the form will be submitted.

You'll see that the all validation scripts presented on this and subsequent pages adhere to the same basic format.

Working with different types of FORM elements

Text/Textarea/Password boxes

The value of a text input box (or a textarea or password input) is available using the syntax form.fieldname.value. This is not the case for other input types.


To check whether two inputs have the same is quite simple:

if(form.field1.value == form.field2.value) {
  // values are identical

Note: Make sure to always use == for comparisons. If you use = (the assignment operator) instead then it can take a long time to debug.

and to see if they have different values we just reverse the logic:

if(form.field1.value != form.field2.value) {
  // values are different

If you want to test numeric values (or add or subtract them) then you first have to convert them from strings to numbers. By default all form values are available as strings only.

  var field1 = parseInt(form.field1.value);
  var field2 = parseInt(form.field2.value);
  if(field1 > field2) {
    // field1 as a number is greater than field2 as a number

Note: parseFloat is the same as parseInt except that it works for floating point numbers as well as integers.

Select/Combo/Drop-down boxes

The value of a SELECT input element is accessed using:

var selectBox = form.fieldname;

where fieldname is the SELECT element, which has an array of options and a value selectedIndex that tells you which option has been selected. The illustration below shows this relationship:

Note that the 'I' in selectedIndex needs to be capitalised - JavaScript functions and variables are always case-sensitive.

If you define a value for the OPTION elements in your SELECT list, then .value will return that, while .text will return the text that is visible in the browser. Here's an example of what this refers to:

  <option value="value">text</option>

Note: One of the most common problems for novices is that Internet Explorer allows you to access the value of the selected option using the same format as for text boxes above. This is wrong!

If you just want to check that an option has been chosen (ie. that the SELECT box is no longer in it's default state) then you can use:

  if(form.fieldname.selectedIndex > 0) {
    // an option has been selected
  } else {
    // no option selected


These really are simple:


will return a boolean value (true or false) indicating whether the checkbox is in a 'checked' state.

  function checkForm(form)
    if(form.checkboxfield.checked) {
      alert("The checkbox IS checked");
    } else {
      alert("The checkbox IS NOT checked");
    return false;

Note: You don't need to test using form.checkboxfield.checked == true as the value is already boolean.

Check me!

Radio buttons

Radio buttons are implemented as if they were an array of checkboxes. To find out which value (if any) has been selected, you need to loop through the array until you find which one has been selected:

  function checkRadio(field)
    for(var i=0; i < field.length; i++) {
      if(field[i].checked) return field[i].value;
    return false;

The form handler function is then the following:

  function checkForm(form) 
    if(radioValue = checkRadio(form.radiofield)) {
      alert("You selected " + radioValue);
      return true;
    } else {
      alert("Error: No value was selected!");
      return false;
Red Green Blue

Checkbox arrays

If you're working with arrays of checkboxes to submit data to a server-side script then you might already have some grey hairs from trying to figure out how to validate the input using JavaScript.

The problem is that, to have the data submitted in a 'nice' format to the server, the name attributes of all the checkboxes in the array are often set to the same value: a name ending with []. This makes it difficult to address them directly using JavaScript.

In this example, the checkboxes are defined as:

<input type="checkbox" name="pref[]" value="value"> label
Example: checkbox array

Which of the following pastimes do you enjoy?

Art /Antiques
Computer games
Dining Out
Going to Pubs/Clubs

When you submit the form you will be notified through an alert message how many items you checked, and what they were. This is calculated using a new function:

  // Original JavaScript code by Chirp Internet:
  // Please acknowledge use of this code by including this header.

  function checkArray(form, arrayName)
    var retval = new Array();
    for(var i=0; i < form.elements.length; i++) {
      var el = form.elements[i];
      if(el.type == "checkbox" && == arrayName && el.checked) {
    return retval;

The form handler that calls this function and displays the alerts is as follows:

  function checkForm(form)
    var itemsChecked = checkArray(form, "pref[]");
    alert("You selected " + itemsChecked.length + " items");
    if(itemsChecked.length > 0) {
      alert("The items selected were:\n\t" + itemsChecked);
    return false;

The checkArray function returns an array contains all the select values.

Normally you would modify this so that you could submit or not submit the form based on the number of items selected. For example "at least two" or "no more than five". This should be a simple exercise.

Combining Form Elements in Conditions

In more complicated forms you will want to set conditions on the form that combine multiple elements. For example, a text input that only needs to have a value if a checkbox is checked:

function checkForm(form)

  if(form.checkboxname.checked && (form.textinputname.value == '')) {
    alert('Error: error message');
    return false;


or conditions that vary according to a radio button selection:

function checkForm(form)

  var radioValue = checkRadio(radiofield);
    case 'Red':
      conditions to apply if 'Red' is selected

    case 'Blue':
      conditions to apply if 'Blue' is selected

      conditions to apply in all other cases


Using simple logical operators and the functions supplied above you can do all sorts of client-side form validation. To take things a step further you can even explore Ajax Form Validation which lets you supply real-time feedback using server-side scripts triggered by JavaScript events.

Related Articles

Translate this page to English Translate this page to French Translate this page to Vietnamese

Recent articles
The Possible Working Methods of Python Ideology
JavaScript Research Paper: 6 Writing Tips to Craft a Masterpiece
Learning How to Make Use of New Marketing Trends
5 Important Elements of an E-commerce Website
How To Create A Successful Prototype For Your PCB
WordPress Landing Page Conversion Essentials to Convert More
4 Development Hacks To Make Your Website Launch A Success
Why Data Recovery Software and Services are Important
Why Engineers Specializing in DevOps Are the Wave of the Future
The Ultimate Checklist for HTTP to HTTPS Migration

Top view articles
65 Free JavaScript Photo Gallery Solutions
Top 10 Beautiful Christmas Countdown Timers
Best Free Linux Web Programming Editors
Top 50 Most Addictive and Popular Facebook mini games
Top 10 Free Web Chat box Plug-ins and Add-ons
50+ Beautiful Resources of HTML Form using CSS and JavaScript
Top 10 Best JavaScript eBooks that Beginners should Learn
The Ultimate JavaScript Tutorial in Web Design
HTML5 Web Workers Multithreading in JavaScript
Learn more about JavaScript Inheritance with Tiny JavaScript Example Codes

Free JavaScript Tutorials & Articles