js正则表达式之验证身份证

来源:互联网 发布:seo搜外网 编辑:程序博客网 时间:2024/06/07 15:59

js正则表达式之验证身份证

  • 验证内容
    • 是否是17位数字+1位数字或者X
    • 验证出生日期是否正确
    • 验证最后一位数是否正确

具体实现

  • 验证长度格式是否正确

/^\d{17}(\d|x)$/i

该表达式意思的以数字开头(^)的17个数在加最后一位数是以数字或者x结尾($) , i是忽略大小写

详细学习很看 菜鸟教程-正则表达式

    if (!/^\d{17}(\d|x)$/i.test(value)) {        alert("长度格式错误");        return;    }
  • 验证出生年月是否正确
    • 判断年份是否超过了今年
    • 月份是否超过了12个月 (月份是从0开始,所以要+1)
    • 日是否超过了当月最大日数
    now = new Date();    yYear = Number(value.substr(6,4));    yMonth = Number(value.substr(10,2)) + 1;    yDay = Number(value.substr(12,2));    var birthFlag = false;    if ( yYear <= Number(now.getFullYear()) && yYear > 0 ) {        if ( yMonth <= 12 && yMonth > 0 ) {            // 获取当月天数            preMonth = new Date(yYear,yMonth-1,0);                      if (yDay <= preMonth.getDate() && yDay > 0) {                birthFlag = true;            }        }    }    if (!birthFlag) {        alert("出生年月日有错误");        return;    }
  • 判断最后一个数是否正确
    • 最后一个数要通过一些计算获取,具体计算规则 身份证最后一位数计算规则
    • 该算法摘自网络
    var iSum = 0;    value = value.replace(/x$/i,"a");    for(var i = 17;i >= 0; i--) {        iSum += (Math.pow(2,i) % 11) * parseInt(value.charAt(17 - i),11) ;    }    if(iSum%11!=1) {        alert("最后一位有误");        return;    }

全部代码

<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8" /><title>JavaScript正则表达式验证身份证号码是否合法</title><script >function isVail(value) {    if (!/^\d{17}(\d|x)$/i.test(value)) {        alert("长度格式错误");        return;    }    now = new Date();    yYear = Number(value.substr(6,4));    yMonth = Number(value.substr(10,2)) + 1;    yDay = Number(value.substr(12,2));    var birthFlag = false;    if ( yYear <= Number(now.getFullYear()) && yYear > 0 ) {        if ( yMonth <= 12 && yMonth > 0 ) {            // 获取当月天数            preMonth = new Date(yYear,yMonth-1,0);            if (yDay <= preMonth.getDate() && yDay > 0) {                birthFlag = true;            }        }    }    if (!birthFlag) {        alert("出生年月日有错误");        return;    }    var iSum = 0;    value = value.replace(/x$/i,"a");    for(var i = 17;i >= 0; i--) {        iSum += (Math.pow(2,i) % 11) * parseInt(value.charAt(17 - i),11) ;    }    if(iSum%11!=1) {        alert("最后一位有误");        return;    }    alert("正确");} </script ><body><input  onBlur="isVail(this.value)"/></body></html>

建议: 平时有什么忘记的知识点可以菜鸟教程找到答案~