This tutorial shows how to set up a simple form validation example using a registration form.
We’ll use the jQuery Validation Plugin to validate an HTML form. This plugin’s basic functionality is to specify validation logic and error messages for HTML elements in JavaScript code.
Here’s a live demo of the HTML form validation using jQuery that we’re going to build:
See the Pen
jQuery Form Validation by Pylogix (@Pylogix)
on CodePen.
Key Takeaways:
Table of Contents
- Key Takeaways:
- Understanding Form Validation Approaches
- Step 1: Include jQuery
- Step 2: Include the jQuery Validation Plugin
- Step 3: Create the HTML File
- Step 4: Create Styles for the Form
- Step 5: Create the Validation Logic
- Advanced Validation Techniques
- 1. Custom Validation Methods
- 2. Real-Time Validation
- 3. Asynchronous (Remote) Validation
- 4. Conditional Validation
- 5. Enhancing User Experience
- 6. Security Best Practices
- 7. Common Pitfalls and Solutions
- 8. Accessibility Enhancements
- Conclusion
- Frequently Asked Questions (FAQs)
- What Is jQuery Form Data Validation?
- Why Is Form Data Validation Important?
- How Do I Perform Form Data Validation Using jQuery?
- What Are Some Standard Form Data Validation Constraints?
- Can I Create Custom Validation Constraints?
- How Do I Initiate Form Data Validation Using the jQuery Data Validation Plugin?
- What Happens If a Form Doesn’t Pass Validation?
- How Can I Customize Error Messages in jQuery Form Data Validation?
- Can I Use jQuery Form Data Validation Without the Validation Plugin?
- Are There Alternatives to the Query Validate Plugin?
- Can I Use AJAX to Validate Form Data?
- Is Form Data Validation Only for Client-Side Validation?
- How Can I Handle Form Submission After Validation?
- Can I Use jQuery Form Data Validation with Other JavaScript Frameworks?
- How Do I Implement Real-Time Validation Efficiently?
- Can I Validate Data Asynchronously, Like Checking Username Availability?
- First, include the jQuery library in your HTML code snippet to set up basic form input validation with the jQuery plugin. You can download it from the official website, use a package manager like Bower or npm, or use a CDN.
- After including jQuery, include the jQuery data validation Plugin. This plugin allows you to specify validation logic and error messages for HTML elements in JavaScript code. For example, you can create a basic form with input fields for user information and use the plugin to validate this information.
- To style the form, create a new CSS file and include it in the head section of your HTML code. Then, initialize the jQuery validation on form submit in a new JavaScript(JS) file, specifying each input field’s validation rules and error messages.
- Remember that client-side validation doesn’t replace server-side validation, as a malicious user can still manipulate or bypass the validation rules.
- Explore advanced techniques, such as custom validation methods, real-time validation, and remote validation for server-side checks.
- Follow security best practices by combining client-side and server-side validation to protect against malicious input.
Understanding Form Validation Approaches
Before diving into implementation, let’s compare manual and jQuery data validation plugin approaches to understand why the validation Plugin stands out:
Overall, the jQuery plugin approach offers several advantages:
- Built-in validation methods.
- Automatic error handling.
- Consistent behaviour across forms.
- Easy customization.
- Better code organization.
- Built-in accessibility features.
Since you now have a basic understanding of what JQuery is, let’s get into the steps of building a simple jQuery form validation example. The steps below will give you a clear understanding of how to validate a form before submission.
Step 1: Include jQuery
First, we need to include the jQuery library. At the time of writing, we use the latest version, jQuery 3.7.1.
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 the latest compatible CDN version.
Create a new HTML file named index.html and include jQuery before the closing
tag:
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
The validation Plugin extends jQuery’s capabilities with built-in validation methods.
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 the latest compatible CDN version.
Include the plugin after jQuery:
script src="vendor/jquery-validation/dist/jquery.validate.min.js">script>
Step 3: Create the HTML File
In the registration form, we will use the following user information:
- First name
- Last name
- Password
So, let’s create our basic form containing these input fields:
div class="container">
h2>Registrationh2>
form action="" name="registration">
label for="firstname">First Namelabel>
input type="text" name="firstname" id="firstname" placeholder="John"/>
label for="lastname">Last Namelabel>
input type="text" name="lastname" id="lastname" placeholder="Doe"/>
label for="email">Emaillabel>
input type="email" name="email" id="email" placeholder="john@doe.com"/>
label for="password">Passwordlabel>
input type="password" name="password" id="password" placeholder="●●●●●"/>
button type="submit">Registerbutton>
form>
div>
When integrating this into an actual application, don’t forget to fill in the action attribute in the above code to ensure 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
section of your HTML code snippet:
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");
* {
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;
}
The form will look like the below after this step:
Note: The styles for .error, will display all the error messages.
Step 5: Create the Validation Logic
Finally, we need to initialize the validation plugin. Create a new file js/form-validation.js and reference it after the
script src="js/form-validation.js">script>
Copy the following code into the newly created file:
$(function() {
$("form[name="registration"]").validate({
rules: {
firstname: "required",
lastname: "required",
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
}
},
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"
},
submitHandler: function (form) {
form.submit();
});
});
The above code will perform jQuery validation on form submission.
Advanced Validation Techniques
1. Custom Validation Methods
- Custom validation methods allows to create rules for scenarios that are not covered by the built-in validation options.
- The plugin provides the $.validator.addMethod function to create such rules.
- The below code shows a jQuery validation example for alphanumeric characters (3-20 characters)
$.validator.addMethod("username", function(value, element) {
return this.optional(element) || /^[a-zA-Z0-9]{3,20}$/.test(value);
}, "Username must be 3-20 alphanumeric characters.");
$("form[name="registration"]").validate({
rules: {
username: {
required: true,
username: true
}
}
});
2. Real-Time Validation
- Use event listeners such as onkeyup, onfocusout, and onclick to trigger validations.
- Validate only visible fields to improve responsiveness.
- Use debounced validation for performance optimization.
$("form[name="registration"]").validate({
onkeyup: function(element) {
var validator = this;
setTimeout(function() {
validator.element(element);
}, 300);
}
});
3. Asynchronous (Remote) Validation
- Use the remote method to validate input against a server-side endpoint for scenarios like checking username or email availability.
- Show loading indicators during validation.
- Example: Username availability check
rules: {
username: {
required: true,
remote: {
url: "/check-username",
type: "post",
data: {
username: function() {
return $("#username").val();
}
}
}
}
},
messages: {
username: {
remote: "Username is already taken."
}
}
4. Conditional Validation
- Dynamically set rules based on the form state, such as requiring a shipping address only if a checkbox is selected.
- Example: Validates the address field only when the shipping checkbox is selected.
rules: {
address: {
required: function(element) {
return $("#shipping").is(":checked");
}
}
}
5. Enhancing User Experience
- Error Messages: Customize error messages and placement for a better UI.
errorPlacement: function(error, element) {
error.appendTo(element.parent().find(".error-container"));
}
- Internationalization: Support multiple languages using localized error messages. You can integrate pre-defined language files from the validation plugin, or create custom localization files.
function loadLanguage(lang) {
$.getScript("js/localization/messages_" + lang + ".js", function() {
$("form[name="registration"]").validate();
});
}
loadLanguage('fr');
6. Security Best Practices
- Sanitize input before validation to remove dangerous characters.
- Combine client-side and server-side validation to ensure robust security.
7. Common Pitfalls and Solutions
- Handle dynamically added fields by attaching validation rules dynamically using jQuery selectors.
$("#add-field").click(function() {
$("#new-field").rules("add", {
required: true,
email: true
});
});
- Prevent multiple submissions with a submission lock mechanism.
submitHandler: function(form) {
$("#submit-button").prop("disabled", true);
form.submit();
}
8. Accessibility Enhancements
- Use ARIA attributes (aria-invalid, aria-describedby) for screen readers.
- Ensure all errors are properly announced and navigable.
Conclusion
That’s it, you’re done! Now you know how to set up form data validation with jQuery, complete with a custom validation 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 constraints (for example, by using the browser’s developer tools).
Frequently Asked Questions (FAQs)
What Is jQuery Form Data Validation?
It ensures that user input in HTML forms meets specific criteria before it is submitted to a server, helping prevent incorrect or incomplete data from being processed.
Why Is Form Data Validation Important?
Validation ensures data accuracy, prevents errors, and improves 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 Data Validation Using jQuery?
The plugin can be used to validate data or write custom jQuery code. It simplifies the process by providing pre-built validation logic and error messages.
What Are Some Standard Form Data Validation Constraints?
Validation standards include checking for required fields, valid email addresses (email validation), numeric values, and password complexity. The jQuery data validation plugin offers built-in rules for these scenarios.
Can I Create Custom Validation Constraints?
Yes, you can create custom validation constraints using the jQuery data validation plugin. Define a new validation method and specify its behaviour, such as checking a specific pattern or value.
How Do I Initiate Form Data Validation Using the jQuery Data Validation Plugin?
You typically call the .validate() method on your form element to initiate validation. The jQuery data validation plugin provides this method and sets up the rules and behaviours for validation.
What Happens If a Form Doesn’t Pass Validation?
If a form doesn’t pass validation, the jQuery data validation plugin will prevent it from being submitted and display error messages next to the corresponding input fields. This will give users feedback about what needs to be corrected.
How Can I Customize Error Messages in jQuery Form Data 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 Data Validation Without the Validation Plugin?
Yes, you can perform form data validation using custom jQuery code without relying on the Validation plugin. You need to write JavaScript functions that manually check form inputs and display error messages.
Are There Alternatives to the Query Validate Plugin?
Yes, other form validation libraries and frameworks are available, such as Parsley.js and Formik (for React applications). Additionally, HTML5 introduced built-in form validation attributes and constraints.
Can I Use AJAX to Validate Form Data?
Yes, you can use AJAX 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 Data Validation Only for Client-Side Validation?
Form validation can be performed both on the client and server sides. 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 the 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 Data 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 you integrate the validation logic appropriately.
How Do I Implement Real-Time Validation Efficiently?
To enhance performance, real-time validation can be implemented with debouncing. The “onkeyup” method is used for debouncing input validation.
Can I Validate Data Asynchronously, Like Checking Username Availability?
Yes, jQuery data validation supports asynchronous validation for cases like checking if a username has already been taken. This is done by making an API call in the background and displaying appropriate feedback based on the server’s response.
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
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
© 2000 – 2025 Pylogix Pty. Ltd.