Creating custom validation rules with jQuery can help you ensure that form data meets specific requirements before submission. Here’s how you can implement it effectively:
To create a custom validation rule, you can extend jQuery Validate plugin's default methods. Follow the example below that demonstrates how to create a simple custom validation for an email field to check if it belongs to a specific domain.
$(document).ready(function() {
// Add custom validation method
$.validator.addMethod("domainCheck", function(value, element, param) {
// Regular expression to check if the email belongs to 'example.com'
return this.optional(element) || /^([a-zA-Z0-9._%+-]+)@example\.com$/.test(value);
}, "Email must be from the domain 'example.com'.");
// Initialize validation on the form
$("#myForm").validate({
rules: {
email: {
required: true,
email: true,
domainCheck: true // Apply custom rule
}
},
messages: {
email: {
required: "Please enter your email",
email: "Please enter a valid email address"
}
}
});
});
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?