jQuery Form Validation

Free JavaScript & jQuery Tutorial

Gain deep knowledge about JavaScript and jQuery by learning how to implement form validation using the jQuery Validation Plugin in our comprehensive tutorial.

This exercise is excerpted from Noble Desktop’s past JavaScript training materials. Noble Desktop now teaches JavaScript and the MERN Stack in our Full Stack Development Certificate. To learn current skills in web development, check out our coding bootcamps in NYC and live online.

Note: These materials are provided to give prospective students a sense of how we structure our class exercises and supplementary materials. During the course, you will get access to the accompanying class files, live instructor demonstrations, and hands-on instruction.

Topics covered in this JavaScript & jQuery tutorial:

Initializing the plugin & setting options, Customizing the error messages, Changing the location of the error messages, Styling the error messages

Exercise Preview

form validation jquery

Full-Stack Web Development Certificate: Live & Hands-on, In NYC or Online, 0% Financing, 1-on-1 Mentoring, Free Retake, Job Prep. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

Exercise Overview

Form validation is essential for so many websites. Here we’ll show you how to set up form validation with the popular jQuery Validation Plugin by Jörn Zaefferer, which is easy, fast, flexible, and well-documented.

Getting Started

  1. Open your code editor if it isn’t already open.

  2. Close any files you may have open.

  3. For this exercise we’ll be working with the Form-Validation folder located in Desktop > Class Files > yourname-JavaScript jQuery Class. You may want to open that folder in your code editor if it allows you to (like Visual Studio Code does).

  4. Open application.html from the Form-Validation folder.

  5. Preview the file in a browser.

  6. Without filling out the form, click Create My Account. You’ll be taken to a Thank You page. Obviously, this form needs some validation so that users fill out the proper information.

  7. Hit the back button to return to the form and leave the page open in the browser so you can reload the page as you make changes to the code.

Initializing the Plugin & Setting Options

The jQuery Validation Plugin by Jörn Zaefferer is one of the most popular validation plugins, used by major sites all over the world. We have included it with our class files, but to download future updates, view examples, and read the documentation, go to jqueryvalidation.org

  1. Return to your code editor.

  2. We need to link to the validation plugin. In between the link to jQuery and the link to main.js (around line 67), add the following bold code:

    <script src="js/vendor/jquery-2.1.0.min.js"></script>
    <script src="js/vendor/jquery.validate.min.js"></script>
    <script src="js/main.js"></script>
    
  3. Save the file.

    Now that we’ve linked to the appropriate plugin, we’re ready to initialize it. A single line of jQuery is all we’ll need to select the form and apply the validation plugin.

  4. Open main.js from the js folder in Form-Validation.

  5. Our form has the ID startAccount. Toward the bottom of the file, add this code:

       // Form Validation
       $('#startAccount').validate();
    
    });
    

    This says to validate the startAccount form. Pretty easy so far, right?

  6. As shown in bold below, add a set of curly braces {} inside the validate() method’s parentheses. These will group all the options we’ll add next.

    $('#startAccount').validate({});
    
  7. In between the curly braces of the validate() method, add the bold code below:

    $('#startAccount').validate({
       rules: {
    
       }
    });
    
  8. We’ve already assigned the name values of the inputs in the HTML markup. Now all we have to do is tell the jQuery plugin which elements of the form should be required by targeting the values of the name attributes for each input. We’ll start with the name field. Add the bold code shown below:

    $('#startAccount').validate({
       rules: {
          name: 'required'
       }
    });
    
  9. Save the file.

  10. Switch to the browser and reload application.html.

  11. Without filling out the form, click Create My Account. Look closely to see a message that says, This field is required. The validation plugin puts the error message after the input that has the error. This looks quite confusing, as it sits on the same line as the label for Email Address. We’ll remedy this shortly.

  12. For now, start typing your name into the field and you’ll see the message disappear. Cool beans!

  13. Let’s add the other required fields. Switch back to your code editor.

  14. Add the following bold code. Don’t forget the commas after the first two options!

    $('#startAccount').validate({
       rules: {
          name: 'required',
          email: 'required',
          phone: 'required'
       }
    });
    
  15. Save the file.

  16. Switch to the browser and reload application.html.

  17. Without filling out the form, click Create My Account. Now all the fields except the Comments are required, which is fine because comments are optional.

  18. Type anything into the Email field. It will immediately validate, no matter what you type. We’d like to set the plugin up so that it will check to see if the user inputs a proper email address.

  19. Switch back to your code editor.

  20. Next to email, delete 'required' and replace it with curly braces {}, as follows:

    rules: {
       name: 'required',
       email: {},
       phone: 'required'
    }
    
  21. Now we can set more options for the email field. Inside the {}, set the email to required and tell the validation plugin that a valid email address is required by typing the bold code shown below:

    rules: {
       name: 'required',
       email: {
          required: true,
          email: true
       },
       phone: 'required'
    }
    
  22. Save the file.

  23. Switch to the browser and reload application.html.

  24. Click Create My Account, then try typing into the Email field again. This time you’ll notice that, as you begin to type, the message changes to Please enter a valid email address. Great!

    A valid email follows the pattern of something@something.something. After you type what appears to be a valid email address, the error message disappears.

Customizing the Error Messages

  1. Switch back to your code editor.

  2. Let’s add some customized error messages. Add the bold code shown below. Don’t forget the comma and { } curly braces!

    $('#startAccount').validate({
       rules: {
    

    Code Omitted To Save Space

       },
       messages: {
    
       }
    });
    
  3. Now let’s put in the messages we want. Add the bold code shown below:

    messages: {
       name: 'Required',
       email: 'A valid email is required',
       phone: 'Required'
    }
    
  4. Save the file.

  5. Switch to the browser and reload application.html.

  6. Without filling out the form, click Create My Account. You should see all your custom messages!

Changing the Location of the Error Messages

By default, the form validation plugin puts error messages after their input fields. Instead, we’d like to move the error messages before them, next to the form labels. We can use the errorPlacement option to change the location.

  1. Switch back to your code editor.

  2. Below the messages option, add the bold code shown below. Don’t forget the comma and curly braces!

    messages: {
       name: 'Required',
       email: 'A valid email is required',
       phone: 'Required'
    },
    errorPlacement: function(error, element) {
    
    }
    

    The errorPlacement option accepts a function as its value. The parameter error is the error message, and element is the form element that caused the error. By default, the error message is added after the input element.

  3. Instead, we want to insert the error message before the input. Add the bold code shown below:

    errorPlacement: function(error, element) {
       error.insertBefore();
    }
    

    The insertBefore() function says to insert the error before “something.” We want that “something” to be the element that is causing the error.

  4. Add the bold code shown below:

    errorPlacement: function(error, element) {
       error.insertBefore( element );
    }
    

    This says to insert the error message before the element that causes the error. Our input fields cause the error, so this code will insert the error before the input. Perfect!

  5. Save the file.

  6. Switch to the browser and reload application.html.

  7. Without filling out the form, click Create My Account. You’ll see that the error messages are now before the inputs, as requested.

Styling the Error Messages

The error messages are wrapped in a label tag by default. If you use the DevTools Inspect feature, you’ll see that the plugin also assigns an error class to them. To style them, we need to create a style called label.error.

  1. Switch back to your code editor.

  2. Open main.css from the css folder in Form-Validation.

  3. Scroll to the bottom of the document and add the following rule:

    label.error {
       color: #f00;
    }
    
  4. Save the file.

  5. Switch to the browser and reload application.html.

  6. Without filling out the form, click Create My Account. Nice, hard to miss red errors!

  7. Let’s finish styling the errors. Switch back to main.css in your code editor.

  8. Edit the label.error style by adding the following property declarations:

    label.error {
       color: #f00;
       font-size: 10px;
       text-transform: uppercase;
       margin-left: 5px;
    }
    
  9. Save the file.

  10. Switch to the browser and reload application.html. Without filling out the form, click Create My Account. Looking much better.

    It would also be nice to highlight the input fields. Luckily the plugin attaches an error class to the input fields as well, so this is very easy.

  11. Switch back to your code editor.

  12. After the label.error rule, add the following rule:

    input.error {
       background-color: #fcffad;
    }
    
  13. Save the file.

  14. Switch to the browser and reload application.html. Without filling out the form, click Create My Account. Now the required input fields are highlighted too, improving the usability of the page.

Optional Bonus: Setting a Default Error Message

In our current form, we’re specifying every error message. What if you have a very long form? It would be a pain to have to set every single one. There is a default message, but it might not be exactly what you want. Let’s see how to set a custom default message.

  1. Return to your code editor.

  2. Switch to main.js.

  3. Go to the validate() method and delete the messages for name and phone (around lines 19 and 21). We can leave the email message because we’d like it to be custom. The messages option should look as shown below. Don’t forget to delete the comma after the email!

    messages: {
       email: 'A valid email is required'
    },
    
  4. Save the file.

  5. Switch to the browser and reload application.html.

  6. Without filling out the form, click Create My Account. You’ll see that the default error messages are being displayed again. We want to change them, but before we do so, let’s look at the plugin’s default messages in the JavaScript Console.

  7. Switch back to main.js in your code editor.

  8. The default messages are stored in $.validator.messages. Before the $('#startAccount').validate code around line 9, add the following bold test code so we can see what’s inside it:

    // Form Validation
    console.log( $.validator.messages );
    $('#startAccount').validate({
       rules: {
    
  9. Save the file.

  10. Preview application.html in Chrome (we’ll be using its DevTools).

  11. Hit Cmd–Opt–J (Mac) or Ctrl–Shift–J (Windows) to bring up the Console.

  12. Click on Object in the Console to explore its contents. These are the default messages. Towards the bottom of the list is the default required message that we want to change. Excellent.

  13. Leave the file open in Chrome, with the Console still open as well. We’ll reload the page as we make changes to the code.

  14. Return to your code editor.

  15. Change the log to access the required message (around line 9):

    console.log( $.validator.messages.required );    
    
  16. Save the file.

  17. Return to Chrome and reload the page.

    You should see the default required message displayed. We can change this default message with a single line of code!

  18. Switch back to main.js in your code editor.

  19. Remove the console.log() code (around line 9) and in its place, assign a new required message as follows:

    $.validator.messages.required = 'Required';
    
  20. Save the file.

  21. Return to Chrome and reload the page. Without filling out the form, click Create My Account. You’ll now see your custom “Required” error messages.

    NOTE: If you want to refer to our final code example, go to Desktop > Class Files > yourname-JavaScript jQuery Class > Done-Files > Form-Validation.

How to Learn Coding

Master coding with hands-on training. Learning how to code in JavaScript, Python, and other popular languages can pave the way to a job in tech, such as web development, data science & analytics, or software engineering.

Yelp Facebook LinkedIn YouTube Twitter Instagram