ElementUI表单验证使用

一、设计校验方式:html

  咱们表单验证的rules通常封装一个单独的js文件,好比我以前写的这个博客:vue

  ElementUI使用问题记录:设置路由+iconfont图标+自定义表单验证函数

   能够修改下:公共的校验写在公共里面,个性化的校验写在methods里面post

  :rules="[rules.password,{validator:valPwd,trigger:'blur'}]"this

 

//先导入公共验证文件 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>

二、同时校验多个表单url

  在保存某个页面时,让页面中的两个form都经过校验才能保存,方法其实挺多的,主要是看下这个Promise的写法spa

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("验证经过了"); });

三、只验证表单里面部份内容:好比咱们须要获取验证码的时候,就只须要验证表单里面的手机号就好了设计

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); }) }

  看文档里面都有的code

  咱们也能够封装一下orm

//获取验证码
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) },
相关文章
相关标签/搜索