【问题标题】:denying special characters jQuery Validate拒绝特殊字符jQuery Validate
【发布时间】:2011-11-17 16:53:35
【问题描述】:

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

$.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

因此,如果存在一个允许的字符,则验证将停止工作。我错过了什么吗?

附:我很确定这与插件有关,因为我只用 javascript 测试了正则表达式,它运行良好。

【问题讨论】:

    标签: jquery regex jquery-plugins jquery-validate


    【解决方案1】:

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

    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
    

    【讨论】:

    • 谢谢,这真的帮助了我(我已经挣扎了好几天-.-)。只是为了记录,您的代码中有一个小错误,您忘记转义斜杠。还是我错了?
    • 啊,是的,/ 应该转义,因为它与分隔符匹配。
    • 没有空格怎么办?
    • @SoldierCorp,只需删除 \s
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    相关资源
    最近更新 更多