拒绝特殊字符 jQuery Validate

发布于 2024-12-16 17:36:28 字数 964 浏览 3 评论 0原文

我需要使用插件 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

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

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

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:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

百合的盛世恋 2024-12-23 17:36:28

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

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

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

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

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


在上面的示例中,完整的正则表达式可能类似于以下内容

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

检查一下!

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 -)

Also, if you'd like to allow a ^, it cannot be the first character otherwise regex treats this as a sort of not operator. (e.g., [^abc] matches any character that's not a, b, or 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 " "), '`',
  ;:'",.<>/?\\-]+          '~', '!', '@', '#', '

check it out!

, '%', '^', '&', '*', '(', ')', '+', '=', '{', '}', '|', ';', ':', ''', '"', ',', '.', '<', '>', '/', '?', '\\', '-' (1 or more times (matching the most amount possible)) -------------------------------------------------------------------------------- $ before an optional \n, and the end of the string

check it out!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文