当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JS正则表达式验证中文字符

JS正则表达式验证中文字符

2018年05月07日  | 移动技术网IT编程  | 我要评论

正则表达式:"^[\u4e00-\u9fa5]{0,}$" 、 "/^[\u4e00-\u9fa5]{1,5}$/" 的含义:

在js里,\uxxxx 是转义字符,"xxxx"对应的是16进制unicode编码;

^ 匹配一行的开始。例如正则表达式^123能够匹配字符串"12345"的开始,但是不能匹配"012345";

[\u4e00-\u9fa5] 指匹配在这两个unicode编码之间的字符;

{0,} 重复0到无限次;

$以它为结束,如123$就是只匹配以123结尾的。1234则不能匹配。

就是说匹配以\u4e00-\u9fa5两字符之间的字符任意组成的字符串(可以是1个字符以上的)而且这字符串前后都没有其它字符。

典型应用:

$(function(){
  // 验证联系人
  $('input[name="contacts"]').focus(function(){
    $(this).next().text('只支持中文字符');
  }).blur(function(){
    var pattern = /^[\u4e00-\u9fa5]{1,5}$/;
    if(pattern.test($(this).val())){  //用原生js的test()函数来匹配传入的值,返回布尔值。
      $(this).removeclass('input_err');
      $(this).next().text('√').removeclass('txt_err').addclass('txt_correct');
      istrue=true;
    }else{
      $(this).addclass('input_err');
      $(this).next().text("×").removeclass('txt_correct').addclass('txt_err');
    }
  });
  // 验证手机号码
  $('input[name="tel"]').focus(function(){
    $(this).next().text('座机请用 - 进行分隔');
  }).blur(function(){
    var pattern = /^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$/;
    if(pattern.test($(this).val())){
      $(this).removeclass('input_err');
      $(this).next().text('√').removeclass('txt_err').addclass('txt_correct');
      istrue=true;
    }else{
      $(this).addclass('input_err');
      $(this).next().text("×").removeclass('txt_correct').addclass('txt_err');
      istrue=false;
    }
  });
})

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持移动技术网!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网