前端根据用户的身份证号怎么显示出生日期、性别和年龄呢?
来啊大兄弟!这里你想要的我都有哦!哇哈哈~~~~~
用户需求:根据用户输入的身份证号自动回显出该用户的出生日期、性别和年龄!看我实现吧!
下面是代码
<FormItem label="身份证号:" prop="idNumber" label-for="idNumber" :rules="[{ required: false, message: '身份证号不能为空', trigger: 'blur' },{ validator: this.validID, trigger: 'blur' }]">
<Input v-model="formData.idNumber" placeholder="请填写身份证号" :disabled="params.type" element-id="idNumber" />
</FormItem>
下面是方法
// 身份证验证
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.formData.idNumber;
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 = 1;
else sex = 0;
//性别 ==> 0:男 1:女
// 性别
this.formData.sex = sex;
// 出生日期
this.formData.birthdate = birth;
// 年龄
this.formData.age = age;
},