Vue根据输入的身份证号自动获取性别、出生日期、年龄

在身份证输入框绑定@input事件(在 Input 值改变时触发),代码如下:

1
2
3
<el-form-item label="身份证号" prop="identityCardNo">
<el-input v-model.trim="dataList.identityCardNo" autocomplete="off" placeholder="请输入身份证号" maxlength="18" @input="inputChange"></el-input>
</el-form-item>

js代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//根据身份证号自动生成性别、出生日期和年龄
inputChange() {
const reg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
if (reg.test(this.dataList.identityCardNo)) { // 身份证号码是否合法
var org_birthday = this.dataList.identityCardNo.substring(6, 14);
var org_gender = this.dataList.identityCardNo.substring(16, 17);
var sex = org_gender % 2 == 1 ? "男" : "女";
var birthday = org_birthday.substring(0, 4) + "-" + org_birthday.substring(4, 6) + "-" + org_birthday.substring(6, 8);
var birthdays = new Date(birthday.replace(/-/g, "/"));
let d = new Date();
let age = d.getFullYear() - birthdays.getFullYear() - (d.getMonth() < birthdays.getMonth() || (d.getMonth() == birthdays.getMonth() && d.getDate() < birthdays.getDate()) ? 1 : 0);

// console.log('生日转换时间', birthdays)
// console.log('年龄', age)

// 赋值给表格
this.dataList.sex = sex
this.dataList.birthday = birthday
this.dataList.age = age
} else {
this.dataList.sex = "未填写"
return false
}
},

效果图如下:效果图.png


Vue根据输入的身份证号自动获取性别、出生日期、年龄
https://blog.readcode.top/posts/693d70d0.html
作者
YuBaiCai
发布于
2022年8月26日
许可协议