0

This regarding the JQuery validation plugin. I have a custom method like this.

$.validator.addMethod("USphoneCheck", function(value, element) {
            var phoneNumberPattern = /^\(?(\d{3})\)?[-]?(\d{3})[-]?(\d{4})$/;
            return phoneNumberPattern.test(value);
        }, "Please enter a valid US phone number.");

This is my function call

 cus_phone: {
                    required: false,
                    minlength: 12,
                    USphoneCheck: true
                },

When I run the code without any value I get "Please enter a valid US phone number" message.

This is not required field, But I want to validate when someone entered a value. Am I doing something wrong? Appreciate your help.

Thanks

2
  • inside your function add a condition. if (value !== '') { //do the validation } Commented Oct 28, 2014 at 14:35
  • You must add "OR" this.optional(element) within your return statement. return this.optional(element) || phoneNumberPattern.test(value) This simply makes it "optional". In other words, if you later wanted the field to be required, simply add required: true to the rule declaration without touching this custom method. See the answer within the duplicate. Commented Nov 2, 2014 at 14:59

1 Answer 1

0

Blank wouldn't be validated with that regex try adding a if else statement to say if its blank don't run the function or wrap the entire regex in () and place a ? at the end.

(/^\(?(\d{3})\)?[-]?(\d{3})[-]?(\d{4})$/)?
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your input. It works. Just wondering is there are any other way to do that through jQuery validation plugin? Thanks again.
I'm not familiar with that plugin, however I did find this for you: stackoverflow.com/questions/17970885/… hope it helps.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.