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

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.
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
Launch your preferred code editor and ensure you have a clean workspace for this exercise.
Close any previously opened files to avoid confusion during development.
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.
Open application.html from the Form-Validation folder to examine the base markup structure.
Preview the file in your browser to understand the current user experience.
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.
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
Open Project Files
Navigate to Desktop > Class Files > yourname-JavaScript jQuery Class > Form-Validation folder and open in your code editor
Preview Current State
Open application.html in browser and test the form without validation to see the problem
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.
Return to your code editor and locate the script section of your HTML file.
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>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.
Open main.js from the js folder within your Form-Validation directory.
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.
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({});Within these curly braces, add the rules object that will define our validation logic:
$('#startAccount').validate({ rules: { } });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' } });Save your changes and prepare to test the first validation rule.
Switch to your browser and reload application.html to see the validation in action.
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.
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.
Let's expand our validation to include all critical fields. Return to your code editor.
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' } });Save the file and test your expanded validation rules.
Return to the browser and reload application.html.
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.
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.
Return to your code editor to implement proper email validation.
Replace the simple string value for email with an object that supports multiple validation rules:
rules: { name: 'required', email: {}, phone: 'required' }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.
Save your enhanced validation configuration.
Return to the browser and reload the page to test the improved email validation.
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.Plugin Setup Checklist
Must be placed between jQuery library and your main JavaScript file
Use $('#formId').validate() to activate the plugin
Define which form fields are required and their validation types
Use both required and email validation for email fields
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.
Return to your code editor and locate your validation configuration.
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: { } });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' }Save your customized message configuration.
Return to the browser and reload application.html to see your personalized error messages in action.
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
| Feature | Default Messages | Custom Messages |
|---|---|---|
| Name Field | This field is required | Required |
| Email Field | Please enter a valid email address | A valid email is required |
| Phone Field | This field is required | Required |
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.
Return to your code editor to implement custom error placement logic.
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.
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.
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.
Save your improved error placement configuration.
Return to the browser and reload application.html to evaluate the enhanced layout.
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.
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.
Switch to your CSS editor by opening main.css from the css folder in your Form-Validation directory.
Navigate to the bottom of the stylesheet and add your first error message styling rule:
label.error { color: #f00; }Save the stylesheet and test the basic styling implementation.
Return to the browser and reload application.html.
Submit the incomplete form to see the bold red error messages—immediately more noticeable and professional than the default styling.
Return to main.css to refine the error message appearance with additional professional styling properties.
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; }Save your enhanced error styling.
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.
Return to your stylesheet to add input field highlighting.
After the label.error rule, add styling for invalid input fields that provides clear visual feedback:
input.error { background-color: #fcffad; }Save the complete styling solution.
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
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.
Return to your JavaScript editor and open main.js.
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.
Save the simplified configuration.
Return to the browser and reload application.html to observe the default message behavior.
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.
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: {Save the file with the debugging code.
Open the page in Chrome and access the Developer Tools Console using Cmd–Opt–J (Mac) or Ctrl–Shift–J (Windows).
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.
Keep the Chrome DevTools open for continued testing as we modify the default message system.
Return to your code editor and modify the console.log statement to examine the specific required message:
console.log( $.validator.messages.required );Save and reload the page in Chrome to see the current default required message displayed in the Console.
Now implement the global message override by replacing the debugging code with a direct assignment:
$.validator.messages.required = 'Required';Save your global message configuration.
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
Explore Default Messages
Use console.log($.validator.messages) to view all built-in error messages
Identify Required Message
Access the specific default required message with $.validator.messages.required
Override Default Value
Set custom default with $.validator.messages.required = 'Required'
Setting a custom default message eliminates the need to specify individual messages for every required field in large forms, significantly reducing code maintenance.