siliconrockstar
siliconrockstar

Reputation: 3664

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

Upvotes: 5

Views: 10008

Answers (4)

ajmirani
ajmirani

Reputation: 512

Define Custom Method Here mobile no considers as Indian mobile no length (10 digits).You can change accordingly. Email Regex

$.validator.addMethod("email_or_mobile", function(value, element) {
        return /^\d{10,10}$/.test(value) ||   //Indian Mobile No. Lenth 10 
            /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(value) //email
}, "Please enter valid email or mobile");

Form Validation

 $('#loginForm').validate({
        rules: {

            email: {
                required: true,
                email_or_mobile: true //check custom method
            },
            password: {
                required: true,
            }
        },
        messages: {
            email: {
                required: "Please enter your email/mobile"
            },
            password: {
                required: "Please enter your password",
            }
        },
    });

Upvotes: 2

Manvel
Manvel

Reputation: 808

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

Upvotes: 2

TheTechGuy
TheTechGuy

Reputation: 17374

This is an old question, a better solution now available is jQuery Groups. Example of jQuery Groups. Validation will look like the following

$( "#myform" ).validate({
  rules: {
    mobile_phone: {
      require_from_group: [1, ".phone-group"]
    },
    home_phone: {
      require_from_group: [1, ".phone-group"]
    },
    work_phone: {
      require_from_group: [1, ".phone-group"]
    }
  }
});

Your three fields each will have the class="phone-group".

Make sure to include additional-methods.min.js which is required for groups validation.

Upvotes: 0

siliconrockstar
siliconrockstar

Reputation: 3664

Ok, super simple solution, forgot to post it earlier - intercept the form submission, manually validate first, then trigger plugin validation. Here's an example that requires one of n checkboxes to be selected (adapted from an actual project, so it might have some typos, but you get the jist):

(document).ready(function() {
       // on form submission
       $('form#signup').submit(function() {
                // make sure a checkbox is selected
                var checked = false;
                $('input.checkboxGroupMember').each(function(index) {
                    if ($(this).attr('checked')) {
                        checked = true;
                    }
                });
                if (checked == false) {
                    // do whatever to handle the failure here
                    $('div#feedback').html('Please select a checkbox');
                    return false;
                } else {
                    $('form#signup').validate();
                }

            });

            // once a checkbox is selected, clear feedback
            $('form input.checkboxGroupMember').change(function(index) {
                if ($(this).attr('checked')) {
                    $('div#feedback').empty();
                }
            });

            $('form#signup').validate();
        });

Can be adapted easily to deal with whatever validation is required that you don't want to do via jQuery validation plugin.

Upvotes: 0

Related Questions