1.用自己熟悉的安装工具安装
2.挂载到vue上,我放置的目录如下
挂载代码如下
import VeeValidate from 'vee-validate';
Vue.use(VeeValidate);
3.自己定义贴合项目的词典和规则(配置vee-validate)
我的配置文件放置位置
配置代码
import VeeValidate, { Validator } from 'vee-validate'
import zhCN from 'vee-validate/dist/locale/zh_CN'
// 设置中文
export default async ({ Vue }) => {
Vue.use(VeeValidate, {
events: 'blur',
locale: 'zh_CN',
dictionary: {
'zh_CN': zhCN
}
})
// 自定义字典
const dictionary = {
zh_CN: {
// attributes and messages
messages: {
mobile: field => '请输入正确的' + field,
email: () => '请输入正确的邮箱', // 邮箱输入错误时提示
required: (field) => '请输入' + field, // 输入为空时提示
captcha: field => field + '不正确',
confirmed: (field, [refField]) => `${field}与${refField}输入不一致`
},
// 设置提示的名词
attributes: {
email: '邮箱地址',
mobile: '手机号码',
captcha: '图形验证码',
code: '短信验证码',
password: '密码',
username: '姓名',
gender: '性别'
}
}
}
Validator.localize(dictionary)
// 自定义手机号码验证规则
Validator.extend('mobile', {
// 错误提示
// getMessage: field => '请输入正确的' + field,
// 验证规则
validate: value => /^((13|14|15|17|18)[0-9]{1}\d{8})$/.test(value)
})
Validator.extend('truthy', {
validate: value => !!value
})
}
4.在表单里使用规则,举例——修改手机号码功能
<div class="fromBox">
<q-form class="q-form" @submit="changeMobile">
//原手机号设置只读,不需要校验
<q-input
v-model.trim="formData.mobile"
placeholder="原手机号"
:disable="true"/>
//validate里的data-vv-scope以实现部分校验,命名为beforeSendSms
<q-input
v-model.trim="formData.newMobile"
placeholder="新手机号"
:error="errors.has('beforeSendSms.mobile')"
v-validate="'required|mobile'"
data-vv-scope="beforeSendSms"
type="tel"
name="mobile"
maxlength="11">
<template v-slot:error>
{{ errors.first('beforeSendSms.mobile')}}
</template>
</q-input>
<q-input
v-model.trim="formData.code"
placeholder="请输入短信验证码"
:error="errors.has('code')"
v-validate="'required'"
maxlength="6"
name="code"
>
<template v-slot:append >
<span v-if="vaildTimer" @click.stop="getCode">发送验证码</span>
<span v-else>已发送({{countDown}})</span>
</template>
<template v-slot:error>
{{ errors.first('code') }}
</template>
</q-input>
<q-btn label="确定" unelevated type="submit"/>
</q-form>
</div>
5.在测试中遇见一个问题,校验的提示信息是英文,网上找的方法都试过,一直改不过来。
使用console.log(this.$validator)打印出来
所以我选择将它强制转换成中文
6.更换手机号需要手机短信验证码,首先的第一步校验就在发送验证码这里,校验输入框是否为空、是否是正确格式,代码如下。
// 发送验证码
getCode(){
//beforeSendSms
this.$validator.validate('beforeSendSms.*')
.then(async (valid) => {
console.log("--表单值是否符合规范--")
//valid为true时获取验证码
if(valid){
console.log('--获取短信验证码--',valid)
const {code} = await getSmsCode({
mobile:this.formData.newMobile,
usage:'bind'
})
if(code === 200){
//验证码获取成功后,设置60s定时
this.timer = setInterval(() => {
this.countDown--;
if(this.countDown <= 0){
clearInterval(this.timer)
this.countDown = 60
this.timer = null
}
},1000)
}
if(code !== 200){
// 获取失败
simpleNotify()
}
}
})
实现效果
后面的校验诸如此法。