How do I create custom validation rules with jQuery

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" } } }); });

jQuery custom validation email validation jQuery Validate plugin form validation