range out of order in character class in regex jquery validator [duplicate]

半世苍凉 提交于 2019-12-12 18:17:17

问题


I'm trying to use jquery validator plugin to test a regEx and display an error message when the regex is not matched. Take a look at the code that I have written so far.

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

Also take a look at the js code that I have written below :

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

I just used a simple regEx to allow only a-z alphabets with /^[a-Z]$/.

I don't know why but I'm getting :

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

Please help, thanks in advance :)


回答1:


The error is because a (97) is after Z (90) in the ASCII encoding sequence - so the range is out of order:

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

So this would be valid (but not intuitive):

/^[Z-a]$/

You should use this regex to match letters A to Z for both upper and lower case:

/^[A-Za-z]$/


来源:https://stackoverflow.com/questions/43963412/range-out-of-order-in-character-class-in-regex-jquery-validator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!