ElementUI
引入了 async-validator,在 ElementUI
官方文檔上對一些驗證配置的說明仍是比較模糊的,只是給出了一個簡單的例子。其實對照插件的文檔編寫代碼,會少寫不少代碼,畢竟封裝的仍是比較好的。html
代碼結構<el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="100px" class="demo-dynamic">
<el-form-item prop="email" label="郵箱" :rules="[ { required: true, message: '請輸入郵箱地址', trigger: 'blur' }, { type: 'email', message: '請輸入正確的郵箱地址', trigger: 'blur,change' } ]" >
<el-input v-model="dynamicValidateForm.email"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('dynamicValidateForm')">提交</el-button>
</el-form-item>
<el-form>
複製代碼
先看一個比較簡單的驗證規則的配置:html
一、在
el-form
標籤上綁定model
屬性,值爲定義的表單的數據對象,再配置一個ref
屬性,和model
屬性綁定同一個表單數據對象。model
定義表單字段綁定,ref
定義表單驗證的對象,兩者能夠一致,也能夠不一樣。正則表達式
二、在每一個
el-form-item
(除包裹按鈕的el-form-item
)標籤上設置prop
屬性,值爲表單的數據對象對應的key
值npm
三、爲每一個
el-form-item
(除包裹按鈕的el-form-item
)綁定驗證規則rule
屬性,配置規則下節詳解數組
四、給表單提交按鈕綁定提交驗證表單事件(非必要,可是在提交表單時是必須的)async
JavaScript
代碼結構<script>
export default {
data() {
return {
dynamicValidateForm: {
email: ''
}
};
},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert('submit!');
} else {
console.log('error submit!!');
return false;
}
});
}
}
}
</script>
複製代碼
JavaScript
裏面相對簡單一點函數
一、在
data
裏面定義一個表單字段的數據對象ui
二、定義一個提交按鈕提交的方法,在提交數據以前,實施表單驗證(
this.$refs[formName].validate((valid)
),當驗證經過(valid = true
)後提交數據,驗證不經過(valid = false
)直接return false
。this
一、Validateurl
function(source, [options], callback)spa
source
配置驗證規則的對象(必須)options
配置驗證過程的參數(可選)callback
當驗證完成後執行的回調函數(必須)二、Rules
function(rule, value, callback, source, options)
rule
對字段的驗證規則value
被驗證的字段值callback
驗證完成後的回調函數,接受錯誤提示的數組source
經過驗證的對象options
附加參數options.messages
消息對象,會和默認信息深層合併三、Type
驗證規則設置的類型值
string
: Must be of type string. This is the default type.number
: Must be of type number.boolean
: Must be of type boolean.method
: Must be of type function.regexp
: Must be an instance of RegExp or a string that does not generate an exception when creating a new RegExp.integer
: Must be of type number and an integer.float
: Must be of type number and a floating point number.array
: Must be an array as determined by Array.isArray.object
: Must be of type object and not Array.isArray.enum
: Value must exist in the enum.date
: Value must be valid as determined by Dateurl
: Must be of type url.hex
: Must be of type hex.email
: Must be of type email.四、Required
被驗證的字段,值必須存在
五、Pattern
被驗證的字段值,經過驗證匹配的正則表達式
六、Range
字段值的範圍指定,當驗證的字段值是字符串或者數組時,驗證的是長度。若是是
number
類型時,值必須大於等於min
值, 小於等於max
值。
七、Length
當驗證的字段值是字符串或者數組時, 指定驗證的就是
length
屬性值,若是是number
類型時,驗證數值長度。
八、Enumerable
根據給出的列表值來驗證字段的值
var descriptor = {
role: {type: "enum", enum: ['admin', 'user', 'guest']}
}
複製代碼