一、Element UI Rules簡介
Element UI是一套基於Vue.js2.0的桌面端組件庫。當採用Element UI做表單驗證的時候,可以使用Element UI Rules。Element UI Rules為表單驗證提供了便利。
Element UI Rules使用了async-validator作為底層驗證器。相較於普通的Validator,AsyncValidator支持異步驗證、定製錯誤信息等高級特性。Element UI Rules又在AsyncValidator的基礎上做了一層封裝,讓使用者可以更加便利地使用。
二、使用Element UI Rules進行表單驗證
使用Element UI Rules進行表單驗證可以分為以下幾步驟:
1. 引入相關庫和樣式
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-default/index.css'
import { Validator } from 'vee-validate'
這裡需要注意,Element UI Rules是基於Vee Validate的,所以必須要引入Vee Validate才能正確使用。
2. 新建一個validator
在新建validator的時候,需要調用Vue.use(ElementUI)來啟用Element UI。
Vue.use(ElementUI)
const validator = new Validator({
name: 'required'
})
3. 添加驗證規則
這裡需要使用elementUI的規則拓展函數。
validator.extend('phone', function (value) {
return /(^1[3|4|5|7|8]\d{9}$)|(^[0-9]{3,4}\-[0-9]{7,8}$)/.test(value)
})
4. 在組件中使用validator
將validator作為prop傳入元素中即可。
<element-input
v-model="phone"
placeholder="請輸入您的手機號"
:validator="validator"
rules="required|phone">
</element-input>
這樣,就可以對手機號進行驗證了。如果不滿足規則,會在輸入框下方顯示錯誤提示。
三、Element UI Rules常用規則
1. required
必填驗證。
2. email
郵箱格式驗證。
3. phone
手機號格式驗證。
4. url
url格式驗證。
5. min/max length
最小、最大長度驗證。
6. pattern
正則表達式驗證。
7. custom
自定義驗證規則。
四、總結
Element UI Rules為表單驗證提供了便利,使用起來簡單明了。建議在使用Element UI的時候也使用它提供的表單驗證功能。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/248113.html