【问题标题】:range out of order in character class in regex jquery validator [duplicate]正则表达式 jquery 验证器中字符类的范围乱序[重复]
【发布时间】:2017-05-14 11:36:14
【问题描述】:

我正在尝试使用 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 字母。

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

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

请帮忙,提前谢谢:)

【问题讨论】:

    标签: javascript jquery regex jquery-validate


    【解决方案1】:

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

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

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

    /^[Z-a]$/
    

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

    /^[A-Za-z]$/
    

    【讨论】:

    • 太棒了,它正在工作:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 2019-06-22
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    • 2020-09-16
    相关资源
    最近更新 更多