在vue中饭入,我們使用vuelidate實現表單驗證挪捕,達到限制用戶輸入的目的,以及提交時驗證表單的目的写妥。
查看官方文檔
第一步:安裝
可以通過npm安裝
npm install vuelidate --save
然后導入到main.js中
import Vue from 'vue'
import Vuelidate from 'vuelidate'
Vue.use(Vuelidate)
第二步:在組件中使用
綁定數據需要用==v-model.trim==綁定苇倡,使用this.$v.user.user_name.$touch()
去觸發(fā)驗證事件富纸,this.$v.user.user_name.required
為true時表示驗證通過
<template>
<form>
<input type="text" class="userName" placeholder="請輸入用戶名" v-model.trim="user.user_name">
<input type="button" value="登錄" class="submit" @click="login">
</form>
</template>
import { required} from 'vuelidate/lib/validators'
export default {
data(){
return {
user:{
user_name:"",
}
}
},
validations: {
user: {
user_name: {
required,
},
}
},
methods:{
login(){
this.$v.user.user_name.$touch()
if(!this.$v.user.user_name.required){
Toast('用戶名不能為空');
}
}
}
補充:自定義驗證規(guī)則
新建js文件,在文件中引入
列子:基于正則表達式的驗證器
//js文件
import { helpers } from 'vuelidate/lib/validators'
export var phone = helpers.regex('phone', /^1(3|4|5|7|8)\d{9}$/);
//組件中
import {phone} from "../../api/validate.js"
validations: {
user: {
mobile: {
phone,
},
}
基于定位器的驗證器
如果您想使用locator策略(與sameAs或requiredIf內置驗證器中的定位器策略完全相同)旨椒,您可以使用ref helper來實現這一點晓褪,其方式與在這兩個驗證器中使用定位器的方式完全相同。
import { req, ref, withParams } from './common'
export default (prop) =>
withParams({ type: 'requiredIf', prop }, function(value, parentVm) {
return ref(prop, this, parentVm) ? req(value) : true
})