用着用着elementUI就觉得好用,在vue项目开发的过程中免不了要做form表单的验证,一开始还想着用vee-validate,但感觉太繁琐了,后面放弃了。下面解答下用rules验证两次输入密码不一致如何来做,也是很多朋友问到的问题:
HTML部分:
<el-form :model="msgForm" :rules="rules" label-width="150px" ref="userMsgForm">
<el-form-item label="密码" prop="passwordOnce">
<el-input auto-complete="new-password" clearable="" placeholder="请输入密码" type="password" v-model="msgForm.passwordOnce"></el-input>
</el-form-item>
<el-form-item label="确认密码" prop="passwordTwice">
<el-input auto-complete="new-password" clearable="" placeholder="请再次输入密码" type="password" v-model="msgForm.passwordTwice"></el-input>
</el-form-item>
</el-form>
js部分:
//template页面部分:
export default {
data(){
return {
msgForm:{
password:"",
passwordOnce:'',
passwordTwice:'',
},
rules:{
passwordOnce:[{
validator:(rule,value,callback)=>{
this.$verify.passwordOnce(value,callback,this.msgForm,this.$refs.userMsgForm)
},
trigger:"change"
}],
passwordTwice:[{
validator:(rule,value,callback)=>{
this.$verify.passwordTwice(value,callback,this.msgForm,this.$refs.userMsgForm)
},
trigger:"change"
}]
}
}
},
props:['msgData'],
mounted(){
this.msgForm=JSON.parse(JSON.stringify(this.msgData));//避免双绑
this.$set(this.msgForm,'passwordOnce',this.msgData.password);//未声明变量需要这样写才可编辑
this.$set(this.msgForm,'passwordTwice',this.msgData.password)
}
}
//验证js文件部分:
import Vue from 'vue'
const customValiate={
install(Vue){
Vue.prototype.$verify={
passwordOnce:(value,callback,$msgForm,$userMsgForm)=>{
if(value){
value = value.trim();
if(value.length < 6 || value.length > 20){
return callback(new Error("请输入密码,6-20位"));
}else{
$userMsgForm.validateField('passwordTwice')
return callback();
}
}else{
return callback(new Error("请输入密码,6-20位"));
}
},
passwordTwice:(value,callback,$msgForm,$userMsgForm)=>{
if(value){
value = value.trim();
if(value.length < 6 || value.length > 20){
return callback(new Error("请输入密码,6-20位"));
}else if($msgForm.passwordTwice!=$msgForm.passwordOnce){
return callback(new Error("两次输入密码不一致"));
}else{
return callback();
}
}else{
return callback(new Error("请输入密码,6-20位"));
}
}
}
}
}
Vue.use(customValiate)
上面的validator方法改了一下之后,两个密码验证方法就能都拿到passwordOnce和passwordTwice的值,可以随时进行比较进行报错,还有一句很关键的代码:
$userMsgForm.validateField('passwordTwice')
这句代码意思是单个执行form的passwordTwice值的验证方法,这样做的好处就是不用两个密码输入框都是提示“两次输入密码不一致”,只在第二个输入框提示,使得提示简洁有条理。
还有一个问题就是在给form赋值回填的时候,如果是直接给form表对应的对象赋值this.msgForm=this.msgData;而请求回来的msgData对象中没有passwordOnce和passwordTwice两个参数的话会 导致报错undifined,并且如果直接给passwordOnce和passwordTwice赋值:
this.msgForm.passwordOnce = this.msgData.password;
this.msgForm.passwordTwice= this.msgData.password;
这样赋值会导致input输入框无法修改、输入、编辑,因为返回的数据中可能是没有passwordOnce和passwordTwice两个字段的,而vue中挂载完还未声明的变量是没有getter/setter的,要这么写:
this.$set(this.msgForm,'passwordOnce',this.msgData.password);
this.$set(this.msgForm,'passwordTwice',this.msgData.password);
好了,两次密码一致问题解决!快去试试吧。