How to Set Up Basic jQuery Form Validation in Two Minutes

Share this article

How to Set Up Basic jQuery Form Validation in Two Minutes

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 jQuery plugin is to specify validation rules and error messages for HTML elements in JavaScript code.

Here’s a live demo of the HTML form validation we’re going to build:

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

Step 1: Include jQuery

First, we need to include the jQuery library. The jQuery validation plugin has been tested up to jQuery version 3.1.1, but the demo in this article works perfectly with version 3.4.1, which is the latest one at the time of writing.

You can use any of the following download options:

  • Download it from jquery.com
  • Download it using Bower: $ bower install jquery
  • Download it using npm or Yarn: $ npm install jquery or yarn add jquery
  • Use a CDN: https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/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 github repo
  • Download it using Bower: $ bower install jquery-validation
  • Download it using npm: npm i jquery-validation
  • NuGet: Install-Package jQuery.Validation
  • Use a CDN: https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.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 basic 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.

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;
}

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 (note the error messages, such as what to tell the user if they haven’t entered a valid email address, are defined in messages:)::

<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 complete witth custom error message. 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 (for example, by using the browser’s developer tools).

Frequently Asked Questions (FAQs)

What is jQuery form validation?

It is the process of ensuring that user input in HTML forms meets specific criteria before it’s submitted to a server. It helps prevent incorrect or incomplete data from being processed.

Why is form validation important?

Validation is crucial to ensure data accuracy, prevent errors, and improve user experience. Validating user input helps maintain data integrity and reduces the likelihood of issues arising from incorrect or malicious data.

How do I perform form validation using jQuery?

You can use the plugin or write custom jQuery code to perform form validation. The plugin simplifies the process by providing pre-built validation rules and error messages.

What is the jQuery Validation plugin?

The jQuery Validation plugin is a popular tool that simplifies form validation in web applications. It provides a set of methods and rules to validate form inputs and display meaningful error messages.

How do I include the jQuery Validation plugin in my project?

To use the jQuery Validation plugin, include the jQuery library in your HTML and then include the jQuery Validation plugin script. You can download the plugin or use a CDN for quicker integration.

What are some common form validation rules?

Common validation rules include checking for required fields, valid email addresses (email validation), numeric values, password complexity, and more. The jQuery Validation plugin offers built-in rules for these scenarios.

Can I create custom validation rules?

Yes, you can create custom validation rules using the jQuery Validation plugin. Define a new validation method and specify its behavior, such as checking a specific pattern or value.

How do I initiate form validation using the jQuery Validation plugin?

You typically call the .validate() method on your form element to initiate validation. This method is provided by the jQuery Validation plugin and sets up the rules and behaviors for validation.

What happens if a form doesn’t pass validation?

If a form doesn’t pass validation, the jQuery Validation plugin will prevent the form from being submitted and display error messages next to the corresponding input fields. This gives users feedback about what needs to be corrected.

How can I customize error messages in jQuery form validation?

The plugin allows you to customize error messages for specific validation rules. You can define custom error messages in the validation settings for each input field.

Can I use jQuery form validation without the Validation plugin?

Yes, you can perform form validation using custom jQuery code without relying on the Validation plugin. You would need to write JavaScript functions that check form inputs and display error messages manually.

Are there alternatives to the Query Validate plugin?

Yes, there are other form validation libraries and frameworks available, such as Parsley.js and Formik (for React applications). Additionally, HTML5 introduced built-in form validation attributes and constraints.

Can I use AJAX with form validation?

Yes, you can use AJAX in combination with form validation to perform real-time validation or submit form data asynchronously. This can help enhance user experience by reducing page reloads.

Is form validation only for client-side validation?

Form validation can be performed both on the client side and the server side. Client-side validation improves user experience, while server-side validation is essential to prevent malicious or incorrect data from reaching the server.

How can I handle form submission after validation?

If you’re using the plugin, it will handle form submission automatically if the validation passes. If you’re using custom validation, you can manually submit the form if validation is successful.

Can I use jQuery form validation with other JavaScript frameworks?

Yes, you can use jQuery form validation alongside other JavaScript frameworks. Be cautious about potential conflicts or compatibility issues, and ensure that you integrate the validation logic appropriately.

Maria Antonietta PernaMaria Antonietta Perna
View Author

Maria Antonietta Perna is a teacher and technical writer. She enjoys tinkering with cool CSS standards and is curious about teaching approaches to front-end code. When not coding or writing for the web, she enjoys reading philosophy books, taking long walks, and appreciating good food.

form validationgitCSjQuerynilsonj
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week