【问题标题】:Multiple Regex validation for single value - alphanumeric with allowed special characters issue单个值的多个正则表达式验证 - 带有允许的特殊字符的字母数字问题
【发布时间】:2014-03-07 08:14:13
【问题描述】:

以下是我用于验证输入名称的正则表达式 - 以字母数字开头,允许使用特殊字符。 它接受“sample#@#@invalid”,其中仅验证允许的 ()[].-_& 字符。 哪里做错了有什么帮助?

if(!/[A-Za-z0-9\s\)\(\]\[\._&-]+$/.test(inputText)){
 alert('Field name should be alphanumeric and allowed special characters _ . - [ ] ( ) &');
       }
if(!/^[A-Za-z0-9]/.test(inputText)){
      alert('Field name must start with an alphanumeric');
 }

【问题讨论】:

  • 注意:这两个验证针对同一个输入字段。

标签: javascript jquery regex validation


【解决方案1】:

不要否定测试,而是使用反转字符类的正则表达式:

if(/[^A-Za-z0-9\s)(\][._&-]/.test(inputText)){

由于这不是锚定的,它将匹配输入文本中任何位置允许集之外的任何字符。

function validate() {
    var inputText = document.getElementById("inputText").value;
    if (/[^A-Za-z0-9\s)(\][._&-]/.test(inputText)) {
        alert('Field name should be alphanumeric and alllowed  special characters _ . - [ ] ( ) &');
    }
    if (/^[^A-Za-z0-9]/.test(inputText)) {
        alert('Field name must start with an alphanumeric');
    }
}

DEMO

【讨论】:

  • 可以去掉一些多余的转义:/[^A-Za-z0-9\s)(\]\[._&-]/.
  • 嗨 barmar,我在 jquery 验证器方法中尝试了上述正则表达式,即。而不是 if 循环。使用 ^ 代替 !. 是否有任何限制。
  • 这取决于您对测试结果的处理方式。我得看看你是怎么用它的。
  • 请注意,我的正则表达式用于匹配 failing 输入。如果验证器希望您返回 true 以表示成功,您必须反转结果。
  • 验证器方法my fiddle中使用的相同正则表达式。
【解决方案2】:

这是以字母数字开头,然后是字母数字+特殊字符。

/^[A-Za-z0-9][A-Za-z0-9\(\)\[\]._&-]+$/

这个以字母数字开头,然后只有特殊字符。

/^[A-Za-z0-9][\(\)\[\]._&-]+$/

请注意,我在正则表达式的末尾添加了 $ 符号,以使其锚定在字符串的末尾。

【讨论】:

    【解决方案3】:

    您的正则表达式与给定的输入字符串的“无效”部分匹配,因为根据您给定的正则表达式,此后缀完全有效。也许你应该在你的正则表达式中添加一个起始 ^ 字符,就像你的第二个一样。那么它将与给定的字符串不匹配。

    if(!/^[A-Za-z0-9\s\)\(\]\[\._&-]+$/.test(inputText)){
        alert('Field name should be alphanumeric and allowed special characters _ . - [ ] ( ) &');
    
    }
    if(!/^[A-Za-z0-9]/.test(inputText)){
        alert('Field name must start with an alphanumeric');
    }
    

    我当然更喜欢 Sabuj Hassan 的答案,因为它将两种检查合二为一。

    【讨论】:

    • 我需要对同一个输入字段同时使用两个错误消息。如果我使用 ^ 第一个第二个正则表达式将不会执行。
    猜你喜欢
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多