Basic jQuery Form Validation Example

0 81

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:

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:

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:

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:

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.

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:

Copy the following styles into the newly created file:

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

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:

Copy the following code into the newly created file:

You might also like More from author

Leave A Reply

Your email address will not be published.