否认特殊字符jQuery Validate

Mar*_*rio 10 regex jquery 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 (. , : ; ? ' ' \" - = ~ ! @ # $ % ^ & * ( ) _ + / < > { } )"
);
Run Code Online (Sandbox Code Playgroud)

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

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

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

| `` ° ¬ // This shows the error message but...
test | // This won't show the message
Run Code Online (Sandbox Code Playgroud)

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

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

mač*_*ček 14

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

regex: /^[A-Za-z\d=#$%...-]+$/
Run Code Online (Sandbox Code Playgroud)

替换...为您要允许的所有特殊字符.另外,在上述的例子中,#,$,%,和-将被允许.注意:你不必逃避(大多数)里面的字符[].

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

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


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

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

说明

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
Run Code Online (Sandbox Code Playgroud)

看看这个!