表單驗證的應用場景十分廣泛,因為網站對用戶輸入內容的限制是非常必要的。
在vue中,我們使用vuelidate方便地實現表單驗證。
官方文檔在這里https://monterail.github.io/vuelidate/
1、安裝
- 使用npm安裝:npm install vuelidate --save
- 在main.js中引入:
import Vuelidate from 'vuelidate' Vue.use(Vuelidate)
在組件.vue中引入需要使用的驗證項:
import { required, minLength, maxLength, sameAs } from 'vuelidate/lib/validators'
2、使用
例如我們要寫一個注冊時的表單驗證,需要用戶填寫的信息有:username,phoneNumber,phoneCode,password,confirmPassword。用vuelidate對這些數據進行驗證。代碼很容易懂,就不寫多余的說明了。
.vue中的代碼如下:
data () {
return {
user: {
username:'',
phone: '',
phoneCode: '',
password: '',
confirmPassword: '',
},
}
},
validations: {
user: {
username: {
required,
minLength: minLength(2),
maxLength: maxLength(20)
}
phone: {
required
},
phoneCode: {
required
},
password: {
required,
minLength: minLength(8),
maxLength: maxLength(32)
},
confirmPassword: {
sameAsPassword: sameAs('Password')
}
}
}
截取HTML中手機號,密碼和驗證密碼的代碼如下:
<!--手機號-->
<div class="form-group" :class="{'error': $v.user.phone.$error}">
<span class="message" v-if="!$v.user.phone.required">手機號不能為空</span>
<input type="text" placeholder="手機號"
v-model.trim="user.phone"
@blur="$v.user.phone.$touch()">
</div>
<!--密碼-->
<div class="form-group" :class="{'error': $v.user.password.$error}">
<span class="message" v-if="!$v.user.password.required">密碼不能為空</span>
<span class="message"
v-if="!$v.user.password.minLength">密碼不能小於{{$v.user.password.$params.minLength.min}}位</span>
<span class="message"
v-if="!$v.user.password.maxLength">密碼不能大於{{$v.user.password.$params.maxLength.max}}位</span>
<div class="auth-password">
<input type="password" placeholder="輸入密碼"
v-model.trim="user.password"
@blur="$v.user.password.$touch()" ref="password1">
</div>
</div>
<!--確認密碼-->
<div class="form-group" :class="{'error': $v.user.confirmPassword.$error}">
<span class="message" v-if="!$v.user.confirmPassword.sameAsPassword">兩次輸入的密碼不一樣</span>
<div class="auth-password">
<input type="password" placeholder="確認密碼"
v-model.trim="user.confirmPassword"
@blur="$v.user.confirmPassword.$touch()"
@keyup.enter="register" ref="password2">
</div>
</div>
其中,第21行、32行中的$touch()方法,表示在什么時候執行驗證。
@blur="$v.user.Phone.$touch()"表示blur事件觸發(失去焦點)時驗證。
@input="$v.user.Phone.$touch()"表示input事件觸發(輸入內容發生變化)時驗證。
轉自;https://blog.csdn.net/latency_cheng/article/details/78580820
