regex jquery验证器中字符类中的范围乱序

时间:2017-05-14 11:36:14

标签: javascript jquery regex jquery-validate

我正在尝试使用jquery验证器插件来测试regEx,并在正则表达式不匹配时显示错误消息。看看我到目前为止编写的代码。

<form name="sampleForm" id="sampleForm" class="col-xs-10 col-xs-offset-1" style="margin-top:10px;">
    <input type="text" id="phoneNumber" name="phoneNumber" class="form-control" required/><br/>
    <input type="text" class="form-control" id="name" name="name"/>
    <button type="submit" class="btn btn-success col-xs-4 col-xs-offset-4" style="margin-top:10px;">Submit</button>
</form>   

另请查看我在下面编写的js代码:

<script>
  $().ready(function() {
    $('#sampleForm').validate({
      rules: {
        phoneNumber: {
          required: true,
          nameTest: true
        }
      },
      messages: {
        phoneNumber: {
          required: "Please enter anything"
        }
      }
    });
  });
  jQuery.validator.addMethod("nameTest", function(value, element) {
    return /^[a-Z]$/.test(value);
  }, "success, it's working");
</script>

我只使用一个简单的regEx来仅允许带有/^[a-Z]$/的a-z字母表。

我不知道为什么,但我得到了:

  

无效的正则表达式:/ ^ [a-Z] $ /:字符类

中的范围乱序

请提前帮助,请提供帮助:)

1 个答案:

答案 0 :(得分:4)

错误是因为a(97)在ASCII编码序列中位于Z(90)之后 - 因此范围无序:

&#13;
&#13;
console.log('a'.charCodeAt(0));
console.log('Z'.charCodeAt(0));
&#13;
&#13;
&#13;

所以这是有效的(但不直观):

/^[Z-a]$/

你应该使用这个正则表达式来匹配大写和小写字母A到Z:

/^[A-Za-z]$/