JavaScript Simple Form Validation | PHP Tutorials for Beginners

This tutorial shows the basic form validation using JavaScript. Form validation is one of the most common uses for JavaScript. JavaScript is a quick, easy way to check a user's input for mistakes, typos, and the omission of required fields. Because validation takes place on the client machine, there's no delay for contacting a remote server.

In this example you need to create two files: one for your form and one for the JavaScript validation code (we will include an external JS file).

Step 1 — Create the HTML form (form.html)

<html>
<head>
    <title>JavaScript Form Validation</title>
    <script src="javascript.js" type="text/javascript"></script>
</head>
<body>
<form name="Form" onsubmit="return validate();">
  <table>
    <tr>
      <td>Name:</td>
      <td><input type="text" name="Name"></td>
    </tr>
    <tr>
      <td>Email:</td>
      <td><input type="text" name="Email"></td>
    </tr>
    <tr>
      <td>Pin Code:</td>
      <td><input type="text" name="Pin"></td>
    </tr>
    <tr>
      <td>Country:</td>
      <td>
        <select name="Country">
          <option value="">Select Country</option>
          <option value="1">USA</option>
          <option value="2">JAPAN</option>
          <option value="3">INDIA</option>
        </select>
      </td>
    </tr>
    <tr>
      <td></td>
      <td><input type="submit" value="Submit"></td>
    </tr>
  </table>
</form>
</body>
</html>

Step 2 — Create the JavaScript file (javascript.js)

function validate() {

    if (document.Form.Name.value == "") {
        alert("Please enter your name.");
        document.Form.Name.focus();
        return false;
    }

    if (document.Form.Email.value == "") {
        alert("Please enter your e-mail address.");
        document.Form.Email.focus();
        return false;
    }

    if (document.Form.Pin.value == "" ||
        isNaN(document.Form.Pin.value) ||
        document.Form.Pin.value.length != 6) {
        alert("Please enter a valid 6-digit pin code.");
        document.Form.Pin.focus();
        return false;
    }

    if (document.Form.Country.value == "") {
        alert("Please select your country.");
        document.Form.Country.focus();
        return false;
    }

    return true;
}

The validation function checks each field one at a time. If a field is invalid, it shows an alert and focuses the offending field, returning false to prevent form submission. Only when all fields are valid does it return true.

Hope this tutorial is useful for you. Keep following PHP Tutorial for Beginners for more help.

← Older Post Newer Post →