First day with jQuery Validation but not first day with jQuery. Very simple question: I have three text inputs: name, phone, and email. I want to require name (no sweat) and EITHER phone OR email, and make sure the input is valid in EITHER phone OR email. I've tried this with:
$(document).ready(function() {
$("#contactForm").validate({
debug:true,
rules: {
name: {
required: true
},
email: {
email:true,
required: function(element){
!$("#phone").valid();
}
},
phone: {
phoneUS: true,
required: function(element){
!$("#email").valid();
}
}
},
messages: {
name: "Please specify your name",
email: {
required: "Please enter a valid email"
},
phone: "Please enter a 10 digit phone number"
}
});
});
But it fails because each validity check calls the other, recursing infinitely and crashing the browser.
There has to be some easy way to do this, but I've spent close to two hours on it and it escapes me :(
You can create your own method by
$.validator.addMethod(
"email_or_phone_number",
(value, element) => {
this.optional(element) || /*is optional*/
/^\d{10,11}$/.test(value) || /*is phone number*/
/\S+@\S+\.\S+/.test(value) /*is email*/
},
"Please enter either phone number or e-mail"
);
Now you can use method "email_or_phone_number" For multidata case:
<input type="text" class="{email_or_phone_number:true}" value="" />
You can change regular expression within method by your own needs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With