拒绝特殊字符 jQuery 验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8171085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:09:25  来源:igfitidea点击:

denying special characters jQuery Validate

jqueryregexjquery-pluginsjquery-validate

提问by Mario

I need to validate a textarea using the plugin jQuery Validate, to do that I use a regex and I add a method to the plugin:

我需要使用插件 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 (. , : ; ? ' ' \" - = ~ ! @ # $ % ^ & * ( ) _ + / < > { } )"
);

Then in the options I add the regex:

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

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

This "works" in a certain way, it does detect the invalid characters and displays the message, the problem is it only works when the special characters are the only ones in the box, for instance:

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

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

So if one allowed character is there then the validation just stops working. Am I missing something?

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

P.S. I'm pretty sure this has something to do with the plugin 'cause I've tested the regex with just javascript and it works well.

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

回答by ma?ek

rather than testing for the presence of the special characters, test for only presence of valid characters

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

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

Replace ...with all the special characters you want to allow. In the example above, #, $, %, and -would be allowed. Note: you don't have to escape (most) of the characters inside of the [].

替换...为您想要允许的所有特殊字符。另外,在上述的例子中,#$%,和-将被允许。注意:您不必转义[].

If you'd like to allow a -, it needs to be the last character otherwise regex tries to parse a range. (e.g., [a-c]matches a, b, and c. [a-c-]matches a, b, c, and -)

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

Also, if you'd like to allow a ^, it cannot be the first character otherwise regex treats this as a sort of notoperator. (e.g., [^abc]matches any character that's not a, b, or c)

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



In your example above, the complete regex might look something like this

在上面的示例中,完整的正则表达式可能如下所示

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

Explanation

解释

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!

一探究竟!