正则表达式 jquery 验证器中字符 class 的范围乱序

range out of order in character class in regex jquery validator

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

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

我只是使用了一个简单的正则表达式来只允许带有 /^[a-Z]$/ 的 a-z 字母表。

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

Invalid regular expression: /^[a-Z]$/: Range out of order in character class

请帮忙,提前致谢:)

错误是因为在ASCII编码序列中a(97)在Z(90)之后——所以范围乱序:

console.log('a'.charCodeAt(0));
console.log('Z'.charCodeAt(0));

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

/^[Z-a]$/

您应该使用此正则表达式来匹配字母 A 到 Z 的大小写:

/^[A-Za-z]$/