vue element-ui 通过身份证获取年龄,出生日期
作者:互联网
页面代码:
<el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
<el-form-item label="儿童身份证" prop="idcard">
<el-input v-model="form.idcard" placeholder="请输入儿童身份证" style="width: 220px;"/>
</el-form-item>
</el-dialog>
// 表单校验
rules: {
idcard: [{ required: true, message: '身份证号不能为空', trigger: 'blur' },
{ validator: this.validID, trigger: 'blur' }
]
}
method代码:
// 身份证验证
async validID(rule,value,callback)
{
// 身份证号码为15位或者18位,15位时全为数字,18位前17位为数字,最后一位是校验位,可能为数字或字符X
let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
if (reg.test(value)) {
await this.go(value.length);
callback()
} else {
callback(new Error('身份证号码不正确'))
}
},
// 实现自动生成生日,性别,年龄
go(val) {
let iden = this.form.idcard;
let sex = null;
let birth = null;
let myDate = new Date();
let month = myDate.getMonth() + 1;
let day = myDate.getDate();
let age = 0;
if(val===18){
age = myDate.getFullYear() - iden.substring(6, 10) - 1;
sex = iden.substring(16,17);
birth = iden.substring(6,10)+"-"+iden.substring(10,12)+"-"+iden.substring(12,14);
if (iden.substring(10, 12) < month || iden.substring(10, 12) == month && iden.substring(12, 14) <= day) age++;
}
if(val===15){
age = myDate.getFullYear() - iden.substring(6, 8) - 1901;
sex = iden.substring(13,14);
birth = "19"+iden.substring(6,8)+"-"+iden.substring(8,10)+"-"+iden.substring(10,12);
if (iden.substring(8, 10) < month || iden.substring(8, 10) == month && iden.substring(10, 12) <= day) age++;
}
if(sex%2 === 0)
sex = '0';
else
sex = '1';
//性别 ==> 1:男 0:女
// this.form.sex = sex;
this.form.age = age;
this.form.birthdate = birth;
},
标签:10,iden,vue,element,substring,12,let,ui,sex 来源: https://blog.csdn.net/weixin_56404022/article/details/122230209