1、首先安装vee-validate(指定版本),安装命令如下:
npm i vee-validate@4.0.3
2、在app.vue中写入如下内容:用vee-validate提供的Form组件代替form标签,用Field组件代替input标签,errors是接收校验的错误信息放在v-slot中,errors的键其实就是form中的键,值就是TRUE和FALSE
< template>
< Form ref = " formCom" class = " form" :validation-schema = " MySchema" v-slot = " {errors}" autocomplete = " off" >
< div class = " form-item" >
< div class = " input" >
< Field :class = " {error:errors.account}" v-model = " form.account" name = " account" type = " text" placeholder = " 请输入用户名" > </ Field>
</ div>
< div class = " error" v-if = " errors.account" >
{{errors.account}}
</ div>
</ div>
< div class = " form-item" >
< div class = " input" >
< Field :class = " {error:errors.password}" v-model = " form.password" name = " password" type = " password" placeholder = " 请输入密码" />
</ div>
< div class = " error" v-if = " errors.password" >
{{errors.password}}
</ div>
</ div>
< a @click = " login" href = " javascript:;" class = " btn" > 重置</ a>
</ Form>
</ template>
< script setup >
import schema from './validate-schema'
import { Form, Field } from 'vee-validate'
import { reactive, ref} from "vue" ;
const formCom = ref ( null )
const form = reactive ( {
account : null ,
password : null ,
} )
const MySchema = {
account : schema. account,
password : schema. password,
}
const login = ( ) => {
form. account = null
form. password = null
formCom. value. resetForm ( )
}
</ script>
< style lang = " less" scoped >
.form {
margin-left : 20px;
.form-item {
height : 70px;
box-sizing : border-box;
.input {
width : 300px;
//text-align : center;
line-height : 40px;
height : 40px;
box-sizing : border-box;
margin-bottom : 5px;
input {
height : 100%;
border : 1px solid black;
}
}
}
.error {
color : red;
//margin-top : 2px;
}
}
</ style>
这里边有个特别需要注意的是重置按钮点击后在formCom.value.resetForm()之前要先清空form表单,否则感觉resetForm()无效
3、新建一个叫validate-schema.js作为表单验证,其内容如下:
export default {
account ( value ) {
if ( ! value) return '请输入用户名'
if ( ! / ^[a-zA-Z]\w{5,19}$ / . test ( value) ) return '字母开头且6-20个字符'
return true
} ,
password ( value ) {
if ( ! value) return '请输入密码'
if ( ! / ^\w{6,24}$ / . test ( value) ) return '密码是6-24个字符'
return true
} ,
mobile ( value ) {
if ( ! value) return '请输入手机号'
if ( ! / ^1[3-9]\d{9}$ / . test ( value) ) return '手机号格式错误'
return true
} ,
code ( value ) {
if ( ! value) return '请输入验证码'
if ( ! / ^\d{6}$ / . test ( value) ) return '验证码是6个数字'
return true
} ,
isAgree ( value ) {
if ( ! value) return '请勾选同意用户协议'
return true
}
}
4、效果如下: