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

Sparky
  • 98,165
  • 25
  • 199
  • 285
Perera1987
  • 97
  • 2
  • 10
  • inside your function add a condition. `if (value !== '') { //do the validation } ` – vaso123 Oct 28 '14 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](http://stackoverflow.com/a/26635377/594235). – Sparky Nov 02 '14 at 14:59

1 Answers1

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})$/)?
  • Thanks for your input. It works. Just wondering is there are any other way to do that through jQuery validation plugin? Thanks again. – Perera1987 Oct 28 '14 at 14:43
  • I'm not familiar with that plugin, however I did find this for you: http://stackoverflow.com/questions/17970885/jquery-validate-plugin-dont-evaluate-empty-fields hope it helps. –  Oct 28 '14 at 14:53