三个很有用的正则

[ 不指定 2008/11/14 20:31 | by wxxslt ]
1、/^\S+@\S+\.\S+$/  用于E-mail验证
2、/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/

用于IP地址验证

3、/^\d{17}(\d|X)$/  身份证验证

JS实现:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml...
<html xmlns="http://www.w3.org/1999/xht...
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>验证身份证号码</title>
<script type="text/javascript">
//建立存在地址码及地址名称的数组
var aCity={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古"
      ,21:"辽宁",22:"吉林",23:"黑龙江 ",31:"上海",32:"江苏"
      ,33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南"
      ,42:"湖北 ",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆"
      ,51:"四川",52:"贵州",53:"云南",54:"西藏 ",61:"陕西",62:"甘肃"
      ,63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外 "
      }
function checkCard(cardId){
  var iSum = 0;
  var re = /^\d{17}(\d|X)$/i;
  if(!re.test(cardId)){
    return false;
  }
  cardId = cardId.replace(/X$/i,"a");
  //验证地址码是否合法
  if(aCity[parseInt(cardId.substr(0,2))] == null){
    alert('地址非法!');
    return false;
  }
  //验证出生日期码是否合法
  sBirthday = cardId.substr(6,4)+"-"+Number(cardId.substr(10,2))+"-"+Number(cardId.substr(12,2));
  var date = new Date(sBirthday.replace(/-/g,"/"));
  if(sBirthday!=(date.getFullYear()+"-"+ (date.getMonth()+1) + "-" + date.getDate())){
    alert('出生日期非法!');
    return false;
  }
  //验证检验码是否合法
  for(var i = 17;i>=0;i--){
    iSum += (Math.pow(2,i) % 11) * parseInt(cardId.charAt(17 - i),11);
  }
  if(iSum%11!=1){
    alert("校验码非法!");
    return false;
  }
  alert('地址:'+aCity[parseInt(cardId.substr(0,2))] + "\n"
         + "出生日期:" +sBirthday + "\n"
         + "性别:" + (cardId.substr(16,1)%2?"男":"女"));
}
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
  <label>请输入身份证号码:

  

  <input name="card" type="text" id="card" maxlength="19" />
  </label>
  <p>
    <label>
    <input type="button" name="Submit" value="确定" onclick='checkCard(this.form.card.value)'/>
    </label>
    <label>
    <input type="reset" name="Submit2" value="重置" />
    </label>
  </p>
</form>
</body>
</html>
JS | Comments(0) | Trackbacks(0) | Reads(148)
Add a comment
Nickname [Register]
Password Optional
Site URI
Email
Enable HTML Enable UBB Enable Emots Hidden Remember