1、設計校驗方式:
我們表單驗證的rules一般封裝一個單獨的js文件,比如我之前寫的這個博客:
ElementUI使用問題記錄:設置路由+iconfont圖標+自定義表單驗證
可以修改下:公共的校驗寫在公共里面,個性化的校驗寫在methods里面
:rules="[rules.password,{validator:valPwd,trigger:'blur'}]"
//先導入公共驗證文件 import {validator,getVeriCode} from '@/utils' //data里面 data(){ return {rules:validator} } //在methods里面定義新的驗證函數valPwd methods:{ valPwd(rule, value, callback) { if (!value) { callback(new Error('請再次輸入密碼')); } else if (value !== this.resetPassword.password) { callback(new Error('兩次輸入密碼不一致!')); } else { callback(); } } } //template里面綁定驗證規則 <el-form-item prop="repeatPassword" :rules="[rules.password,{validator:valPwd,trigger:'blur'}]"> <el-input type="password" v-model="resetPassword.repeatPassword" placeholder="重復密碼"></el-input> </el-form-item>
2、同時校驗多個表單
在保存某個頁面時,讓頁面中的兩個form都通過校驗才能保存,方法其實挺多的,主要是看下這個Promise的寫法
var p1=new Promise(function(resolve, reject) { this.$refs[form1].validate((valid) => { if(valid){ resolve(); } }) }); var p2=new Promise(function(resolve, reject) { this.$refs[form2].validate((valid) => { if(valid){ resolve(); } }) }); Promise.all([p2,p1]).then(function(){ alert("驗證通過了"); });
3、只驗證表單里面部分內容:比如我們需要獲取驗證碼的時候,就只需要驗證表單里面的手機號就行了
getCode(){ this.$refs['resetPassword'].validateField('phone',(validMessage)=>{ if(validMessage != ""){ return false; } this.codeDisabled = true; let countTime = setInterval(() => { --this.countdown; if(this.countdown == 0){ clearTimeOut(countTime); this.countdown = 60; this.codeDisabled = false; return; } },1000); }) }
看文檔里面都有的
我們也可以封裝一下
//獲取驗證碼
export const getVeriCode = (vueInstance,formName,phone) => { vueInstance.$refs[formName].validateField('phone',(validMessage)=>{ if(validMessage != ""){ return false; } getVeriCodeApi(phone).then((res) =>{ if(res.status === 200){ vueInstance.$message({ message:'驗證碼已發送,請注意查收。', type:'success' }) } }) vueInstance.codeDisabled = true; let countTime = setInterval(() => { --vueInstance.countdown; if(vueInstance.countdown == 0){ clearInterval(countTime); vueInstance.countdown = 60; vueInstance.codeDisabled = false; return; } },1000); }) } //調用
getCode(){ getVeriCode(this,'login_code',this.login_code.phone) },