否认特殊字符jQuery Validate

时间:2011-11-17 16:53:36

标签: jquery regex jquery-plugins jquery-validate

我需要使用插件jQuery Validate验证textarea,为此我使用正则表达式并向插件添加方法:

$.validator.addMethod(
    "regex",
    function(value, element, regexp) {
        var check = false;
        var re = new RegExp(regexp);
        return this.optional(element) || re.test(value);
    },
    "No special Characters allowed here. Use only upper and lowercase letters (A through Z; a through z), numbers and punctuation marks (. , : ; ? ' ' \" - = ~ ! @ # $ % ^ & * ( ) _ + / < > { } )"
);

然后在选项中添加正则表达式:

comments:{
    required: true,
    maxlength: 8000,
    regex: /[^A-Za-z\d\-\=\~\!@#\%&\*\(\)_\+\\\/<>\?\{\}\.\$‘\^\+\"\';:,\s]/
}

这种“工作”以某种方式,它确实检测到无效字符并显示消息,问题是它只在特殊字符是框中的唯一字符时才起作用,例如:

| `` ° ¬ // This shows the error message but...
test | // This won't show the message

因此,如果有一个允许的字符,那么验证就会停止工作。我错过了什么吗?

P.S。我很确定这与插件有关,因为我用javascript测试了正则表达式并且效果很好。

1 个答案:

答案 0 :(得分:14)

而不是测试是否存在特殊字符,只测试是否存在有效字符

regex: /^[A-Za-z\d=#$%...-]+$/

...替换为您要允许的所有特殊字符。在上面的示例中,将允许#$%-。注意:您不必转义[]内的(大多数)字符。

如果你想允许-,它必须是最后一个字符,否则正则表达式试图解析一个范围。 (例如,[a-c]匹配a,b和c。[a-c-]匹配a,b,c和 - )

此外,如果您想允许^,则它不能是第一个字符,否则正则表达式将此视为一种not运算符。 (例如,[^abc]匹配任何不是a,b或c)的字符


在上面的示例中,完整的正则表达式可能看起来像这样

regex: /^[A-Za-z\s`~!@#$%^&*()+={}|;:'",.<>\/?\\-]+$/

解释

NODE                     EXPLANATION
--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  [A-Za-                   any character of: 'A' to 'Z', 'a' to 'z',
  z\s`~!@#$%^&*()+={}|     whitespace (\n, \r, \t, \f, and " "), '`',
  ;:'",.<>/?\\-]+          '~', '!', '@', '#', '$', '%', '^', '&',
                           '*', '(', ')', '+', '=', '{', '}', '|',
                           ';', ':', ''', '"', ',', '.', '<', '>',
                           '/', '?', '\\', '-' (1 or more times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string

check it out!

相关问题