Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Validation : require either valid phone or valid email

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 :(

like image 560
siliconrockstar Avatar asked Oct 10 '22 07:10

siliconrockstar


1 Answers

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

like image 195
Manvel Avatar answered Oct 13 '22 11:10

Manvel