开发者

jQuery validation regex: textarea contains phrases

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.a开发者_JAVA百科ddMethod(
    "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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜