无法验证连字符

Unable to validate hyphens

本文关键字:连字符 验证      更新时间:2023-09-26

我正在尝试验证包含"字母数字字符、支持的符号和空格"的名称。在这里,我只需要允许单个hyphen(-),而不允许双重hyphen(--)

这是我的代码如下:

$.validator.addMethod(
  'alphanumeric_only',
  function (val, elem) {
    return this.optional(elem) || /^[^*~<^>+('--)/;|.]+$/.test(val);
  },
  $.format("shouldn't contain *.^~<>/;|")
);

上面的代码甚至不允许使用单个hyphen(-)。如何允许使用单连字符,但防止使用双连字符。非常感谢您的帮助。

为此,您需要一个负前瞻断言:

/^(?!.*--)[^*~<^>+()'/;|.]+$/

应该这样做。

解释:

^                 # Start of string
(?!               # Assert it's impossible to match the following:
 .*               #  any string, followed by
 --               #  two hyphens
)                 # End of lookahead
[^*~<^>+()'/;|.]+ # Match a string consisting only of characters other than these
$                 # End of string

如果您的字符串可以包含换行符,这并不是说这可能会失败。如果可以,使用

/^(?!['s'S]*--)[^*~<^>+()'/;|.]+$/

我建议您使用白名单而不是黑名单。然而,这是有效的:

        <input type="text" id="validate"/>
    <script>
        $('#validate').keyup(function(){
            val = this.value;
            if(/([*.^~<>/;|]|--)/.test(val)) this.style.backgroundColor='red';
            else this.style.backgroundColor='';
        });
    </script>