jQuery — Validation
Basic Validation
$("form").submit(function(e) {
var name = $("#name").val();
if (name === "") {
alert("Name is required");
e.preventDefault();
}
});
jQuery Validate Plugin
$("form").validate({
rules: {
name: { required: true, minlength: 2 },
email: { required: true, email: true },
age: { required: true, number: true, min: 18 }
},
messages: {
name: "Please enter your name",
email: "Please enter a valid email",
age: "You must be at least 18"
}
});
Validation Rules
| Rule | Description |
|---|---|
| required | Field must not be empty |
| Must be valid email format | |
| url | Must be valid URL |
| number | Must be a number |
| minlength | Minimum character length |
| maxlength | Maximum character length |
| min | Minimum numeric value |
| max | Maximum numeric value |
Custom Validation
$.validator.addMethod("phone", function(value) {
return /^\d{10}$/.test(value);
}, "Please enter a valid 10-digit phone number");
Validate on Submit
if ($("form").valid()) {
// Form is valid
$("form").submit();
}
Highlighting Errors
$("form").validate({
highlight: function(element) {
$(element).addClass("error");
},
unhighlight: function(element) {
$(element).removeClass("error");
}
});
Mini Practice
- Validate a form with required fields
- Add email validation
- Create a custom validation rule
- Style error messages
Up Next
Continue with Forms — working with forms in jQuery.
Related Topics
Frequently Asked Questions about Validation
What is Validation in jQuery?
Validation is a fundamental concept in jQuery. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Validation?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Validation.
Why is Validation important in jQuery?
Validation is essential for jQuery development. Understanding this concept will help you write better code and solve real-world problems more effectively.