regex jquery验证器中字符类中的范围乱序 [英] range out of order in character class in regex jquery validator

查看:46
本文介绍了regex jquery验证器中字符类中的范围乱序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>   

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

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>

我只使用一个简单的regEx来只允许z字母与 / ^ [ AZ] $ /

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

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

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


无效正则表达式:/ ^ [aZ] $ /:字符类中的顺序无序

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

请提前帮助,谢谢:)

推荐答案

错误是因为 a (97)在<$ c之后ASCII编码序列中的$ c> Z (90) - 因此范围无序:

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]$/

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

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

/^[A-Za-z]$/

这篇关于regex jquery验证器中字符类中的范围乱序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆