Skip to main content
April 1, 2026Dan Rodney/11 min read

jQuery Form Validation

Master jQuery form validation with professional techniques

jQuery Validation Plugin Overview

The jQuery Validation Plugin by Jörn Zaefferer is one of the most popular validation plugins, used by major sites worldwide. It's easy, fast, flexible, and well-documented.

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

Core Validation Concepts

Plugin Initialization

Learn how to set up the jQuery Validation Plugin with proper script linking and basic configuration. Understanding the foundation is crucial for success.

Custom Error Messages

Replace default error messages with branded, user-friendly text that matches your application's tone and style guidelines.

Visual Styling

Apply CSS styling to error messages and form fields to create a cohesive, professional user experience that guides users effectively.

Exercise Preview

form validation jQuery

Exercise Overview

Form validation remains a cornerstone of professional web development, directly impacting user experience and data quality. In this comprehensive tutorial, we'll implement robust client-side validation using the battle-tested jQuery Validation Plugin by Jörn Zaefferer. This plugin has powered form validation on millions of websites since its inception, offering developers a reliable, flexible, and well-documented solution that integrates seamlessly with existing jQuery workflows. While modern frameworks have introduced new validation approaches, this plugin continues to be an excellent choice for projects requiring proven stability and extensive customization options.

Form Validation Necessity

Without proper validation, users can submit incomplete forms and be redirected to thank you pages with invalid data. This creates poor user experience and unreliable data collection.

Getting Started

  1. Launch your preferred code editor and ensure you have a clean workspace for this exercise.

  2. Close any previously opened files to avoid confusion during development.

  3. Navigate to the Form-Validation folder located in Desktop > Class Files > yourname-JavaScript jQuery Class. If you're using a modern editor like Visual Studio Code, WebStorm, or Sublime Text, open the entire folder as a project to enable better file navigation and IntelliSense support.

  4. Open application.html from the Form-Validation folder to examine the base markup structure.

  5. Preview the file in your browser to understand the current user experience.

  6. Test the form's current behavior by clicking Create My Account without filling out any fields. Notice how the form submits successfully to a Thank You page—a significant usability issue that we'll address through comprehensive validation.

  7. Use your browser's back button to return to the form, keeping this tab open for real-time testing as we implement our validation logic.

Initial Setup Process

1

Open Project Files

Navigate to Desktop > Class Files > yourname-JavaScript jQuery Class > Form-Validation folder and open in your code editor

2

Preview Current State

Open application.html in browser and test the form without validation to see the problem

3

Prepare Development Environment

Keep the browser page open for live reloading as you make code changes

Initializing the Plugin & Setting Options

The jQuery Validation Plugin by Jörn Zaefferer stands as one of the most trusted validation solutions in the JavaScript ecosystem, deployed across enterprise applications and small projects alike. While we've included the plugin files with this tutorial, professional developers should bookmark jqueryvalidation.org for future updates, comprehensive documentation, and advanced implementation examples that showcase the plugin's full capabilities.

  1. Return to your code editor and locate the script section of your HTML file.

  2. Add the validation plugin reference between the jQuery library and your main.js file (approximately line 67). This loading order ensures jQuery is available before the plugin initializes:

    <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 to ensure the plugin dependency is properly registered.

    With the plugin properly linked, we can now initialize validation with a single, elegant line of jQuery. This demonstrates the plugin's developer-friendly design philosophy.

  4. Open main.js from the js folder within your Form-Validation directory.

  5. Locate the form element with ID startAccount and add the following validation initialization code toward the bottom of the file:

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

    This concise syntax targets our specific form and applies the validation plugin with default settings—an excellent starting point that we'll customize extensively.

  6. Enhance the validation call by adding a configuration object within the parentheses. Add the curly braces as shown below to prepare for our custom options:

    $('#startAccount').validate({});
  7. Within these curly braces, add the rules object that will define our validation logic:

    $('#startAccount').validate({
       rules: {
    
       }
    });
  8. The plugin leverages the HTML name attributes to identify form elements for validation. Begin by making the name field required, demonstrating the plugin's intuitive syntax:

    $('#startAccount').validate({
       rules: {
          name: 'required'
       }
    });
  9. Save your changes and prepare to test the first validation rule.

  10. Switch to your browser and reload application.html to see the validation in action.

  11. Attempt to submit the form without entering a name. You'll notice the error message "This field is required" appears immediately after the input field. While functional, this placement creates visual confusion by positioning the error next to the Email Address label—an issue we'll resolve shortly.

  12. Type any text into the name field and watch the error message disappear instantly, demonstrating the plugin's real-time validation capabilities that enhance user experience.

  13. Let's expand our validation to include all critical fields. Return to your code editor.

  14. Add validation rules for the email and phone fields, paying careful attention to the comma syntax required for object properties:

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

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

  17. Submit the empty form to see validation messages for all required fields. Notice that the Comments field remains optional, which aligns with typical user registration patterns.

  18. Test the email field by entering random text. The plugin currently accepts any input as valid, but email fields require more sophisticated validation to ensure data quality.

  19. Return to your code editor to implement proper email validation.

  20. Replace the simple string value for email with an object that supports multiple validation rules:

    rules: {
       name: 'required', 
       email: {}, 
       phone: 'required'
    }
  21. Configure the email field to require both presence and proper formatting by adding these validation rules:

    rules: {
       name: 'required', 
       email: {
          required: true, 
          email: true
       }, 
       phone: 'required'
    }

    The email: true rule leverages the plugin's built-in email validation, which checks for the standard email format pattern.

  22. Save your enhanced validation configuration.

  23. Return to the browser and reload the page to test the improved email validation.

  24. Submit the form, then begin typing in the Email field. The error message now dynamically updates to "Please enter a valid email address" as you type, providing immediate feedback about formatting requirements.

    Professional email validation follows the pattern something@something.something, and the error message will disappear once you enter a properly formatted address, creating a smooth user experience.

A single line of jQuery is all we'll need to select the form and apply the validation plugin.
The jQuery Validation Plugin's simple initialization process makes it accessible for developers of all skill levels.

Plugin Setup Checklist

0/4

Customizing the Error Messages

While default error messages provide basic functionality, professional applications require customized messaging that aligns with brand voice and user experience standards. Let's implement custom messages that are more concise and user-friendly.

  1. Return to your code editor and locate your validation configuration.

  2. Add a messages object alongside your rules configuration, maintaining proper JSON syntax with commas and braces:

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

    Code Omitted To Save Space

    }, 
       messages: {
    
       }
    });
  3. Define custom error messages that match your form fields, creating more concise and professional messaging:

    messages: {
       name: 'Required', 
       email: 'A valid email is required', 
       phone: 'Required'
    }
  4. Save your customized message configuration.

  5. Return to the browser and reload application.html to see your personalized error messages in action.

  6. Test the form by clicking Create My Account without completing any fields. Your custom messages now appear, providing a more polished user experience that can be easily adapted to match your organization's style guidelines.

Default vs Custom Error Messages

FeatureDefault MessagesCustom Messages
Name FieldThis field is requiredRequired
Email FieldPlease enter a valid email addressA valid email is required
Phone FieldThis field is requiredRequired
Recommended: Custom messages provide better brand consistency and user experience

Changing the Location of the Error Messages

Strategic placement of error messages significantly impacts form usability. The plugin's default behavior places errors after input fields, which can create visual confusion in complex layouts. By repositioning errors before the inputs, we create a cleaner, more intuitive interface that guides users more effectively.

  1. Return to your code editor to implement custom error placement logic.

  2. Add the errorPlacement option after your messages configuration, using a function to define custom positioning logic:

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

    The errorPlacement function receives two critical parameters: error represents the generated error message element, while element refers to the form input that triggered the validation failure. This flexibility allows for sophisticated error positioning strategies.

  3. Implement the logic to position error messages before their corresponding inputs rather than after:

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

    The insertBefore() method requires a target element to specify where the error should be positioned in the DOM structure.

  4. Complete the positioning logic by specifying the target element:

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

    This configuration instructs the plugin to insert each error message immediately before its associated input field, creating better visual alignment with field labels.

  5. Save your improved error placement configuration.

  6. Return to the browser and reload application.html to evaluate the enhanced layout.

  7. Test the form submission without completing required fields. The error messages now appear before the inputs, creating a cleaner visual hierarchy that better supports user comprehension and form completion.

Error Placement Strategy

By default, error messages appear after input fields, which can disrupt form layout. Using errorPlacement function with insertBefore() method positions errors more intuitively next to labels.

Styling the Error Messages

Professional form validation requires thoughtful visual design to ensure error messages are both noticeable and aesthetically integrated. The plugin automatically wraps error messages in label elements with an "error" class, providing targeted styling opportunities that we'll leverage to create polished, attention-grabbing error displays.

  1. Switch to your CSS editor by opening main.css from the css folder in your Form-Validation directory.

  2. Navigate to the bottom of the stylesheet and add your first error message styling rule:

    label.error {
       color: #f00;
    }
  3. Save the stylesheet and test the basic styling implementation.

  4. Return to the browser and reload application.html.

  5. Submit the incomplete form to see the bold red error messages—immediately more noticeable and professional than the default styling.

  6. Return to main.css to refine the error message appearance with additional professional styling properties.

  7. Enhance the error styling with typography and spacing improvements that create visual hierarchy without overwhelming the form:

    label.error {
       color: #f00;
       font-size: 10px;
       text-transform: uppercase;
       margin-left: 5px;
    }
  8. Save your enhanced error styling.

  9. Return to the browser and reload the page, then test the form submission. The error messages now display with improved typography that's both attention-grabbing and professionally styled.

    To complete the user experience, we should also provide visual feedback on the input fields themselves. The plugin conveniently adds an "error" class to invalid inputs, enabling coordinated styling.

  10. Return to your stylesheet to add input field highlighting.

  11. After the label.error rule, add styling for invalid input fields that provides clear visual feedback:

    input.error {
       background-color: #fcffad;
    }
  12. Save the complete styling solution.

  13. Return to the browser and reload application.html for final testing. Submit the incomplete form to see both highlighted input fields and styled error messages working together to create an intuitive, professional validation experience that guides users toward successful form completion.

Styling Components

Error Message Labels

Style with label.error selector using red color, small font size, uppercase text, and proper spacing for visibility.

Input Field Highlighting

Use input.error selector to apply background color highlighting that draws attention to fields requiring correction.

Visual Error Feedback Benefits

Pros
Red error text provides immediate visual feedback
Uppercase styling increases message prominence
Input field highlighting improves usability
Consistent spacing maintains form layout integrity
Cons
Too much red styling can overwhelm users
Small font sizes may reduce accessibility

Optional Bonus: Setting a Default Error Message

In enterprise applications with extensive forms, manually specifying every error message becomes inefficient and maintenance-intensive. The plugin's default message system provides a solution, but these generic messages often don't align with your application's tone and branding. Here's how to establish custom default messages that maintain consistency across your entire application.

  1. Return to your JavaScript editor and open main.js.

  2. Locate the validate() method and streamline the messages object by removing individual messages for name and phone fields, retaining only the specialized email message:

    messages: {
       email: 'A valid email is required'
    }, 

    Remember to remove the trailing comma after the email message to maintain valid JavaScript syntax.

  3. Save the simplified configuration.

  4. Return to the browser and reload application.html to observe the default message behavior.

  5. Submit the incomplete form to see the plugin's built-in default messages displayed for name and phone fields while your custom email message remains unchanged.

  6. To understand the default message system, let's examine the plugin's internal message object. Return to main.js and add debugging code before your validation initialization:

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

  8. Open the page in Chrome and access the Developer Tools Console using Cmd–Opt–J (Mac) or Ctrl–Shift–J (Windows).

  9. Click on the "Object" entry in the Console to explore the complete list of default validation messages. Locate the "required" message that we want to customize—this represents the global default for all required field validations.

  10. Keep the Chrome DevTools open for continued testing as we modify the default message system.

  11. Return to your code editor and modify the console.log statement to examine the specific required message:

    console.log( $.validator.messages.required );
  12. Save and reload the page in Chrome to see the current default required message displayed in the Console.

  13. Now implement the global message override by replacing the debugging code with a direct assignment:

    $.validator.messages.required = 'Required';
  14. Save your global message configuration.

  15. Return to Chrome and reload the page. Test the form submission to see your customized "Required" message applied consistently across all required fields, while maintaining your specialized email validation message.

    This technique proves invaluable for large-scale applications where consistent messaging enhances user experience while reducing code maintenance overhead.

    NOTE: For reference implementation and additional advanced techniques, examine the complete code examples in Desktop > Class Files > yourname-JavaScript jQuery Class > Done-Files > Form-Validation.

Default Message Configuration

1

Explore Default Messages

Use console.log($.validator.messages) to view all built-in error messages

2

Identify Required Message

Access the specific default required message with $.validator.messages.required

3

Override Default Value

Set custom default with $.validator.messages.required = 'Required'

Efficiency Tip

Setting a custom default message eliminates the need to specify individual messages for every required field in large forms, significantly reducing code maintenance.

Key Takeaways

1jQuery Validation Plugin requires only a single script link and one line of initialization code to get started with form validation
2Form validation rules are defined using field name attributes, making it easy to specify required fields and validation types like email
3Custom error messages can be configured through the messages object to match your application's branding and tone
4Error message placement can be controlled using the errorPlacement function with insertBefore() method for better user experience
5CSS styling for error messages uses label.error and input.error selectors to provide visual feedback through colors and highlighting
6Default error messages can be overridden globally using $.validator.messages.required for efficient management of large forms
7The plugin automatically handles real-time validation, showing and hiding error messages as users interact with form fields
8Professional form validation improves data quality and user experience by preventing submission of incomplete or invalid information

RELATED ARTICLES