0

I'm using jQuery's Validation plugin to validate a form, which is going well. I know there are built-in methods to check for an email address, URL, etc. However, now I want to check for a specific regex (^[a-zA-Z\ ]+$ in this case, but I'm looking for a general answer).

How can I let the plugin check for a regular expression?

3
  • 2
    please try it out and post some code so that we can help you with the particular issue. Commented Apr 12, 2013 at 10:37
  • @Ejay try what out? I have no idea what I should do... Commented Apr 12, 2013 at 10:39
  • It seems that you want custom validation docs.jquery.com/Plugins/Validation/Validator/… Commented Apr 12, 2013 at 10:41

2 Answers 2

1

Going by the documentation you've linked to, you'd want to use addMethod.

Presumably (I've not used this plugin) with something like:

$.validator.addMethod("myMethod", function(text) { 
    var regex = /^[a-zA-Z\ ]+$/;
    return regex.test(text); 
}, "Custom error message");

You could go one step further by making your own regex method:

$.validator.addMethod("regex", function(text, pattern) {
    return pattern.test(text); 
}, "Pattern does not match.");
Sign up to request clarification or add additional context in comments.

1 Comment

Cool, thanks! For reference: the documentation says it is not clean to make a general method: "While the temptation is great to add a regex method that checks it's parameter against the value, it is much cleaner to encapsulate those regular expressions inside their own method."
1

You need to do something like this:

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

);

now all you need to do to validate against any regex is this:

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

I had this sample with me so thought of just pasting it. you are defining a method that checks again your regex pattern and in the below code you apply the rule for particular control(s). change the validation condition and regex pattern with your requirements.

Comments

Your Answer

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