0

I am adding in a custom method for the jQuery Validation plugin to check for a valid phone number. However, I want this field to be optional, and not required. For some reason, when I add the following code in, it is making fields with the class "phone" required too. Any ideas what I'm doing wrong?

$.validator.addMethod("phone", function(ph, element) {
    var stripped = ph.replace(/[\s()+-]|ext\.?/gi, "");
    // 10 is the minimum number of numbers required
    return ((/\d{10,}/i).test(stripped));
});

$('#custom').validate({
    errorPlacement: function(error, element) {
        return true;
    }
}); 

<input type="text" class="phone" name="phone_1" id="phone_1">

1 Answer 1

4

You'll want to update your method so it returns true if the phone field is empty. Something like:

$.validator.addMethod("phone", function(ph, element) {
    if(ph=='') return true;
    var stripped = ph.replace(/[\s()+-]|ext\.?/gi, "");
    // 10 is the minimum number of numbers required
    return ((/\d{10,}/i).test(stripped));
});

It's going to run the method on all of the phone fields, so this way you allow them to pass on untested unless they actually contain content.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! I wonder how we can change it to work for a URL field?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.