JavaScript Form Validation | PHP Tutorial For Beginners

Why Client-Side Form Validation?

Forms validation on the client-side is essential — it saves time and bandwidth and gives you more options to point out to the user where they've gone wrong. However, you should also use server-side validation, because visitors may use an old browser or have JavaScript disabled. Client and server-side validation complement each other and should not be used independently.

Why Is Client-Side Validation Good?

  • It's fast: if something's wrong, the event is triggered upon submission of the form or on change of focus.
  • You can display one error at a time and focus on the wrong field, helping ensure the user correctly fills in all details.

The two key approaches to client-side form validation are:

  1. Display errors one by one, focusing on the offending field.
  2. Display all errors simultaneously, server-side validation style.

The better method for client-side is to show one error at a time — this lets you highlight only the incorrectly completed field, making it easier for the visitor to revise and resubmit.

Complete Example

<html>
<head>
<title>JavaScript Form Validation</title>
<script type="text/javascript">

function form_validate() {

    if (document.Form.Name.value == "") {
        alert("Please enter your first 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.Zip.value == "" ||
        isNaN(document.Form.Zip.value) ||
        document.Form.Zip.value.length != 5) {
        alert("Please enter a zip code in the format *****.");
        document.Form.Zip.focus();
        return false;
    }
}

</script>
</head>
<body>

<form name="Form" onsubmit="return(form_validate());">
  <table>
    <tr>
      <td>First Name:</td>
      <td><input type="text" name="Name" /></td>
    </tr>
    <tr>
      <td>E-Mail Address:</td>
      <td><input type="text" name="EMail" /></td>
    </tr>
    <tr>
      <td>Postal Code:</td>
      <td><input type="text" name="Zip" /></td>
    </tr>
    <tr>
      <td></td>
      <td><input type="submit" value="Submit" /></td>
    </tr>
  </table>
</form>

</body>
</html>

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

← Older Post Newer Post →