JavaScript
Article
By Julian Motz , Sam Deering

Basic jQuery Form Validation Example (2mins)

By Julian Motz , Sam Deering
Help us help you! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

This popular article was updated on 18th August, 2016 to correct some minor errors and reflect the current version of the library. Comments pertaining to the old article were deleted.

This tutorial shows you how to set up a basic form validation with jQuery, demonstrated by a registration form.

We’re going to use the jQuery Validation Plugin to validate our form. The basic principle of this plugin is to specify validation rules and error messages for HTML elements in JavaScript.

Here’s a live demo of what we’re going to be building:

See the Pen Basic jQuery Form Validation Example by SitePoint (@SitePoint) on CodePen.

Step 1: Include jQuery

First, we need to include jQuery v1.x as the validation plugin is currently only compatible with jQuery versions lower than 2.0.

There are the following download options:

  • Download it from jquery.com
  • Download it using Bower: $ bower install jquery#1.x --save-dev
  • Download it using npm: $ npm install jquery@1.x --save-dev
  • Use a CDN: https://cdn.jsdelivr.net/jquery/1.12.4/jquery.min.js

Create a new HTML file named index.html and include jQuery before the closing </body> tag:

<!-- Change the "src" attribute according to your installation path -->
<script src="vendor/jquery/dist/jquery.min.js"></script>

If you’d like to use Bower or npm but aren’t familiar with them, you might be interested in these two articles:

Step 2: Include the jQuery Validation Plugin

Choose between:

  • Download it from the plugin’s website
  • Download it using Bower: $ bower install jquery-validation
  • Download it using npm: $ npm install jquery-validation
  • Use a CDN: https://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js

Include the plugin after jQuery:

<!-- Change the "src" attribute according to your installation path -->
<script src="vendor/jquery-validation/dist/jquery.validate.min.js"></script>

Step 3: Create the HTML Form

For the registration we want to collect the following user information:

  1. First name
  2. Last name
  3. Email
  4. Password

So, let’s create our form containing these input fields:

<div class="container">
  <h2>Registration</h2>
  <form action="" name="registration">

    <label for="firstname">First Name</label>
    <input type="text" name="firstname" id="firstname" placeholder="John"/>

    <label for="lastname">Last Name</label>
    <input type="text" name="lastname" id="lastname" placeholder="Doe"/>

    <label for="email">Email</label>
    <input type="email" name="email" id="email" placeholder="john@doe.com"/>

    <label for="password">Password</label>
    <input type="password" name="password" id="password" placeholder="&#9679;&#9679;&#9679;&#9679;&#9679;"/>

    <button type="submit">Register</button>

  </form>
</div>

When integrating this into a real application, don’t forget to fill in the action attribute, to make sure the form is submitted to the correct destination.

--ADVERTISEMENT--

Step 4: Create Styles for the Form

Create a new file, css/styles.css, and include it in the <head> section of your HTML file:

<link rel="stylesheet" href="css/style.css"/>

Copy the following styles into the newly created file:

@import url("https://fonts.googleapis.com/css?family=Open+Sans");

/* Styles */
* {
  margin: 0;
  padding: 0;
}

body {
  font-family: "Open Sans";
  font-size: 14px;
}

.container {
  width: 500px;
  margin: 25px auto;
}

form {
  padding: 20px;
  background: #2c3e50;
  color: #fff;
  -moz-border-radius: 4px;
  -webkit-border-radius: 4px;
  border-radius: 4px;
}
form label,
form input,
form button {
  border: 0;
  margin-bottom: 3px;
  display: block;
  width: 100%;
}
form input {
  height: 25px;
  line-height: 25px;
  background: #fff;
  color: #000;
  padding: 0 6px;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}
form button {
  height: 30px;
  line-height: 30px;
  background: #e67e22;
  color: #fff;
  margin-top: 10px;
  cursor: pointer;
}
form .error {
  color: #ff0000;
}

If you’re using Compass (SCSS) you can alternatively use the following to style the form:

@import "compass";
@import url("https://fonts.googleapis.com/css?family=Open+Sans");

/* Color settings */
$formBg: #2c3e50;
$formColor: #fff;
$inputBg: #fff;
$inputColor: #000;
$buttonBg: #e67e22;
$buttonColor: #fff;
$errorMsgColor: #ff0000;

/* Styles */
* {
  margin: 0;
  padding: 0;
}

body {
  font-family: "Open Sans";
  font-size: 14px;
}

.container {
  width: 500px;
  margin: 25px auto;
}

form {
  padding: 20px;
  background: $formBg;
  color: $formColor;
  @include border-radius(4px);

  label,
  input,
  button {
    border: 0;
    margin-bottom: 3px;
    display: block;
    width: 100%;
  }
  input {
    height: 25px;
    line-height: 25px;
    background: $inputBg;
    color: $inputColor;
    padding: 0 6px;
    @include box-sizing(border-box);
  }
  button {
    height: 30px;
    line-height: 30px;
    background: $buttonBg;
    color: $buttonColor;
    margin-top: 10px;
    cursor: pointer;
  }
  .error {
    color: $errorMsgColor;
  }
}

Note the styles for .error, which will be used for validation error messages.

Step 5: Create the Validation Rules

Finally, we need to initialize the form validation plugin. Create a new file js/form-validation.js and reference it after the <script> tag of the jQuery Validation plugin:

<script src="js/form-validation.js"></script>

Copy the following code into the newly created file:

// Wait for the DOM to be ready
$(function() {
  // Initialize form validation on the registration form.
  // It has the name attribute "registration"
  $("form[name='registration']").validate({
    // Specify validation rules
    rules: {
      // The key name on the left side is the name attribute
      // of an input field. Validation rules are defined
      // on the right side
      firstname: "required",
      lastname: "required",
      email: {
        required: true,
        // Specify that email should be validated
        // by the built-in "email" rule
        email: true
      },
      password: {
        required: true,
        minlength: 5
      }
    },
    // Specify validation error messages
    messages: {
      firstname: "Please enter your firstname",
      lastname: "Please enter your lastname",
      password: {
        required: "Please provide a password",
        minlength: "Your password must be at least 5 characters long"
      },
      email: "Please enter a valid email address"
    },
    // Make sure the form is submitted to the destination defined
    // in the "action" attribute of the form when valid
    submitHandler: function(form) {
      form.submit();
    }
  });
});

Conclusion

That’s it, you’re done! Now you have an idea how to set up form validation with jQuery. Please keep in mind that this doesn’t replace server-side validation. It’s still possible for a malicious user to manipulate or bypass the validation rules (e.g. using the browser’s developer tools).

Login or Create Account to Comment
Login Create Account
Recommended
Sponsors
Get the latest in JavaScript, once a week, for free.