要实现这样一个功能,先给身份证号码进行校验,当身份证输入正确之后,js截取号码中的生日,当鼠标移出输入框的时候,出生日期自动渲染,要实现其实很简单,直接上代码:
1.单单只想截取出身份证号码中的生日可以这样写就可以实现啦
下面的判断分为一代身份证15位,二代身份证18位,现在大部分使用的都是18位吧,但也做了相应的判断,直接调用即可
getBirth_date : function(idCard) {
var birthday = "";
if(idCard != null && idCard != ""){
if(idCard.length == 15){
birthday = "19"+idCard.substr(6,6);
} else if(idCard.length == 18){
birthday = idCard.substr(6,8);
}
birthday = birthday.replace(/(.{4})(.{2})/,"$1-$2-");
}
return birthday;
},
2.以下是实现与出生日期双向绑定的详细代码:
HTML:
<el-form
ref="form"
label-width="120px"
:rules="rules"
:model="ruleForm"
>
<el-form-item
label="身份证号"
size="mini"
class="part"
prop="id_card"
>
<el-input
v-model="ruleForm.id_card"
@change="changes(ruleForm.id_card)"
></el-input>
</el-form-item>
<el-form-item
label="出生日期"
size="mini"
class="part"
label-width="100px"
>
<el-date-picker
type="date"
placeholder="选择日期"
v-model="birth_date"
style="width: 100%;"
></el-date-picker>
</el-form-item>
</el-form>
注意!使用校验规则的表单,在data中定义的时候必须要放在一个对象中,:model="ruleForm"这行代码一定要写,不写不生效!
js:
export default {
name: "",
data() {
//自定义校验规则
var checkIdCard = (rule, value, cb) => {
const regIdCard = /^[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 (regIdCard.test(value)) {
return cb();
}
cb(new Error("您输入的身份证号码不是有效格式"));
};
return {
ruleForm: {
id_card: "", //身份证
},
birth_date: null, //出生日期
rules: {
id_card: [
{ required: true, message: "请输入身份证", trigger: "blur" },
{ validator: checkIdCard, trigger: "blur" },
],
},
methods:{
changes(idCard) {
var birthday = "";
if (idCard != null && idCard != "") {
if (idCard.length == 15) {
birthday = "19" + idCard.substr(6, 6);
} else if (idCard.length == 18) {
birthday = idCard.substr(6, 8);
}
birthday = birthday.replace(/(.{4})(.{2})/, "$1-$2-");
}
this.birth_date=birthday
console.log(birthday);
// return birthday;
},
}
},
element ui 官网也有详细介绍哦------https://element.eleme.cn/#/zh-CN/component/form
这样也就实现了自定义校验的规则,可以在项目中使用了!