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.

1 Answer 1

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+)?)$/ })
Sign up to request clarification or add additional context in comments.

Comments

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.