1

I am trying to add a regex validation to my JQueryUI validator following the guidance of jQuery validate: How to add a rule for regular expression validation?

$.validator.addMethod(
        "regex",
        function(value, element, regexp) {
            var re = new RegExp(regexp);
            return this.optional(element) || re.test(value);
        },
        "Please check your input."
);

and

$("#Textbox").rules("add", { regex: "^[a-zA-Z'.\\s]{1,40}$" })

The regex that I would like to include is

^(\d+(?:(?: \d+)*\/\d+)?)$

Which can be seen at http://regex101.com/r/cB3fQ1/2

When I enter the regex into the jquery, no entries pass. This is how I entered it

$("#Textbox").rules("add", { regex: "^(\d+(?:(?: \d+)*\/\d+)?)$" })

Is it because I am wrapping it in a string and some syntac is conflicting? I am inexperienced at regex and am not sure how to go about trouble shooting this. Please advise me if you see where my error is. Thank you.

Community
  • 1
  • 1
MicFin
  • 2,431
  • 4
  • 32
  • 59

1 Answers1

1

You will need to double escape the backslashes since you're entering regex as string:

$("#Textbox").rules("add", { regex: "^(\\d+(?:(?: \\d+)*\/\\d+)?)$" })

OR else use regex literal:

$("#Textbox").rules("add", { regex: /^(\d+(?:(?: \d+)*\/\d+)?)$/ })
anubhava
  • 761,203
  • 64
  • 569
  • 643