views:

55

answers:

1

I'm trying to check a textarea to make sure it contains text phrase(s).

This is what I have so far but it's not working:

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

$("#article_text").rules("add", { regex: "/test phrase/i" });

Any ideas? Ideally, i'd like it to check for multiple phrases and display the error if any one of them isn't included in the textarea.

+1  A: 

When using RegExp() you should leave off the / and flags, it should just be:

$("#article_text").rules("add", { regex: "test phrase" });

You can test it here. But since you want flags, a better way is to just use it directly, not creating from a string, like this:

$.validator.addMethod("regex", function(value, element, regexp) {
  return this.optional(element) || regexp.test(value);
}, "Please include your keyword(s).");

Then you'd call it like this:

$("#article_text").rules("add", { regex: /test phrase/i });

You can test that version out here.

Nick Craver
Works great, thanks Nick. What would be the best way to require two different phrases? Ex: "test phrase" and "another phrase" would both need to be included.
Ricky
@Ricky - if you're doing a regex, just `|` separate them for an "or" combo
Nick Craver
What would i use to require both phrases to be present?
Ricky
@Ricky - you could add another regex rule (via `rules("add")`) if you want to do a check for both, I'm not an expert on regexes though, may want to ask a question specifically on that tagged regex to get those regex gurus to take a look.
Nick Craver
I added another rule, that'll work for now.One problem though, it still lets me submit it even if the phrases arent' included. It displays the error, but doesn't stop the submission. Any ideas?
Ricky
@Ricky - sounds like a JavaScript error occuring after this, anything in the console?
Nick Craver
I think it has to do with my ajax submit. http://jsfiddle.net/TEmXu/ I know somethings not right there, but not sure. Appreciate the help.
Ricky
@Ricky - it shouldn't be reaching that code if it's invalid, but when it does, it'll need to be `data: $(form).serialize()` since `form` is a DOM element, not a jQuery object.
Nick Craver
Yeah, i was doing the ajax submit via a submit bind, but changed it to the submitHandler instead and fixed the serialize part. Works now, you rock - thx.
Ricky
@Ricky - welcome :)
Nick Craver