一. 首先需效验输入身份证信息是否正确:
const sfzhChange = () => { // 效验身份证号格式 const reg = /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/; };
二.绑定输入框 input 事件:
<el-form-item label="证件号码"> <el-input v-model="addFroms.idcard" autocomplete="off" maxlength="18" placeholder="请输入证件号码" @input="sfzhChange" /> </el-form-item>
三.
if (reg.test(addFroms.idcard)) { //获取出生日期 addFroms.birthday = addFroms.idcard.substring(6, 10) + '-' + addFroms.idcard.substring(10, 12) + '-' + addFroms.idcard.substring(12, 14); //获取性别 if(addFroms.idcard.substr(16, 1) % 2 == 1){ addFroms.sex = "男"; }else{ addFroms.sex = "女"; } }
四. 完整代码:
const sfzhChange = () => { // 效验身份证号格式 const reg = /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/; if (reg.test(addFroms.idcard)) { //获取出生日期 addFroms.birthday = addFroms.idcard.substring(6, 10) + '-' + addFroms.idcard.substring(10, 12) + '-' + addFroms.idcard.substring(12, 14); //获取性别 if(addFroms.idcard.substr(16, 1) % 2 == 1){ addFroms.sex = "男"; }else{ addFroms.sex = "女"; } } };
效果: