官网上面有正则函数异步三种验证效果,但是并没有详细说明多个表单验证该如何实现,这里提一下
首先要有form标签
<van-form @submit="onSubmit">
这个标签包裹提交按钮
onSubmit(values) { console.log("submit", values); },
之后在里面写input框
<van-field v-model="form.tel" type="tel" label="手机号码" :rules="telRules" />
更改rules用函数进行校验
trigger里有两个参数一个是onBlur一个是onChange这个可以根据项目实现进行更换
在提交按钮中写入native-type="submit"来验证表单内容
native-type="submit"
效果实现如下:
局部校验
如果想需要得到单个字段的检验结果就需要绑定对应的方法
给form设置一个ref值,通过this.$refs.值.validate('里面的方法名').then(()=>).catch(()=>{})来判断是否通过
this.$refs.form.validate('emailRules').then(()=>{ console.log('成功 !'); }).catch(()=>{ console.log('失败'); })
全局校验
如果是全局校验则无需写括号中的name
this.$refs.form.validate().then(()=>{ console.log('成功 !'); }).catch(()=>{ console.log('失败'); })
这里看一下hooks的写法:
/* Hooks正则验证 */ export default function(){ // 手机号 const telRules = [ { required: true, message: "手机号码不能为空", trigger: "onChange" }, { }, ]; // 密码 const psdRules = [ { required: true, message: "密码不能为空", trigger: "onChange" }, { validator: (value: any) => { return /^(?=.*[a-z])(?=.*\d)[^]{8,16}$/.test(value); }, message: "密码必须包含数字,字母,且不少于8位", trigger: "onBlur", }, ]; // 姓名 const nameRules = [ { required: true, message: "姓名不能为空", trigger: "onChange" }, { validator: (value: any) => { return /^[\u2E80-\u9FFF]+$/.test(value); }, message: "姓名输入不合法", trigger: "onBlur", }, ]; // 身高 const heightRules = [ { required: true, message: "身高不能为空", trigger: "onChange" }, { validator: (value: any) => { return /^(0{1}|[1-9]\d{0,3}|.{0})$/.test(value); }, message: "请输入正确的身高", trigger: "onBlur", }, ]; const weightRules = [ { required: true, message: "体重不能为空", trigger: "onChange" }, { validator: (value: any) => { return /^(0(\.\d{1}){0,1}|[1-8]\d{1,3}(\.\d{1}){0,1}|9\d{1,2}(\.\d{1}){0,1}|999(\.0){0,1}|.{0})$/.test( value ); }, message: "请输入正确的体重", trigger: "onBlur", }, ]; return{ telRules, psdRules, nameRules, heightRules, weightRules } }
在页面中引入:
<van-field v-model="phone" name="phone" label="手机" type="tel" placeholder="请填写手机号码" :rules="telRules" /> import resgisterSelector from "../hooks/registerSelector"; setup(){ const { dietitianName, teamDoctorName, therapistsName, coachName, yingyangshi, duiyi, kangfushi, jiaolianyuan, } = resgisterSelector(); return{ dietitianName, teamDoctorName, therapistsName, coachName, yingyangshi, duiyi, kangfushi, jiaolianyuan, } }