单个值的多重正则表达式验证 - 允许特殊字符问题的字母数字

时间:2014-03-07 08:14:13

标签: javascript jquery regex validation

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

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');
 }

3 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

这是从字母数字开始,然后是字母数字+特殊字符。

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

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

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

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

答案 2 :(得分:0)

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

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的答案,因为它将两张支票合二为一。