jQuery Simple Form Validation | PHP Tutorial For Beginners

This tutorial demonstrates jQuery form validation using the jQuery Validation Plugin. The plugin makes it easy to add rules for required fields, valid email addresses, and required dropdown selections — with inline error messages displayed in red.

Complete Example

<html>
<head>
  <title>jQuery Form Validation</title>
  <script type="text/javascript"
    src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
  <script type="text/javascript"
    src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
  <script type="text/javascript">
  $(document).ready(function() {
      $("#form1").validate({
          debug: false,
          rules: {
              name:     "required",
              dropdown: "required",
              email: {
                  required: true,
                  email:    true
              }
          },
          messages: {
              name:     "Please enter your name.",
              email:    "Please enter a valid email address.",
              dropdown: "Please select an option from the dropdown."
          },
          submitHandler: function(form) {
              $.post('nextstep.php', $("#form1").serialize(), function(data) {
                  $('#result').html(data);
              });
          }
      });
  });
  </script>
  <style>
    label.error { width: 250px; display: inline; color: red; }
  </style>
</head>
<body>
  <form name="form1" id="form1" action="" method="POST">
    <label for="name">Name</label>
    <input type="text" name="name" id="name" size="30" value="">
    <br>
    <label for="email">Email</label>
    <input type="text" name="email" id="email" size="30" value="">
    <br>
    Please select a city:
    <select name="dropdown" id="dropdown">
      <option value="">None</option>
      <option value="mumbai">Mumbai</option>
      <option value="delhi">Delhi</option>
      <option value="pune">Pune</option>
    </select>
    <br>
    <input type="submit" name="submit" value="Submit">
  </form>
  <div id="result"></div>
</body>
</html>

How It Works

  • $("#form1").validate() attaches the validator to the form on DOM ready.
  • The rules object maps field names to validation rules ("required", email: true, etc.).
  • The messages object provides custom error text displayed inline next to each field.
  • The submitHandler only fires when the form is valid — it posts the data to nextstep.php via Ajax and injects the response into #result.

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

← Older Post Newer Post →