terminate.jpg

首页

技术分享

自定义表单验证

ElementUI的表单验证的常规用法比较简单好用

<template>
<form :model="formData" ref="formRef">
<el-form-item label="Name" prop="name">
<el-input v-model="formData.name" :disabled="isDefault" size="small" class="rule-list-dialog-type" />
</el-form-item>
</form>
</template>
<script>
export default {
data() {
return {
formData: {
name: ''
},
rules: {
name: [
{ required: true, message: 'Please type rule name', trigger: 'blur' }
]
}
}
},
methods: {
onSubmit(){
this.$refs.formRef.validate(valid => {
if (valid) {
... do submit
} else {
... show error message
}
})
}
}
}
</script>

注意的地方在于:

  • form标签一定要有:modelref='xxx' 这两个属性, 前者用于验证其寻找数据,后者用于手动触发验证动作
  • el-form-item标签一定要有 prop='xxx'属性,这个就是用来验证的那个变量
  • data里必须有rules 变量,并且包含最基础的必填验证

稍微复杂一点的就是自定义的组件用自定义的验证器

<template>
<form :model="formData" ref="formRef">
<el-form-item label="Name" prop="name">
<el-input v-model="formData.name" :disabled="isDefault" size="small" class="rule-list-dialog-type" />
</el-form-item>
<el-form-item label="Scope" prop="scopeList">
<!--这是一个自定义的组件-->
<scope v-model="formData.scopeList" :scopes="formData.scopeList" @removeTag="onRemoveTag" @addTag="onAddClick" />
</el-form-item>
</form>
</template>
<script>
export default {
data() {
var listValidation = (rule, value, callback) => {
if (value.length === 0) {
this.$message({
message: 'Please provide at least one item.',
type: 'error'
})
callback(new Error('Must at least one item'))
}
callback()
}
return {
formData: {
name: '',
custemData: []
},
rules: {
name: [
{ required: true, message: 'Please type rule name', trigger: 'blur' }
],
custemData: [
{ validator: listValidation }
]
}
}
},
methods: {
onSubmit(){
this.$refs.formRef.validate(valid => {
if (valid) {
... do submit
} else {
... show error message
}
})
}
}
}
</script>

这里的注意点就是自定义验证的函数里,如果验证成功也必须调用callback函数

Comments:

captcha