第一种必填校验
{ required: true, message: '请输入活动名称', trigger: 'blur' },
第二种字符数校验
{ min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
第三种正则校验
{pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '请输入正确格式,可保留两位小数',trigger: 'change' }
第四种类型校验
{ type: 'number',min: 2, message: '请输入不少于2个字符', trigger: 'blur' },
自定义校验规则
{
validator(_, value, callback){
// rule:采用的规则
// value: 被校验的值
// callback是回调函数,
// 如果通过了规则检验,就直接调用callback()
// 如果没有通过规则检验,就调用callback(错误对象,在错误对象中说明原因)
// 例如:callback(new Error('错误说明'))
if(value === '123456'){
callback(new Error('密码不能为123456'))
} else{
callback()
}
// console.log(rule, value, callback)
},
trigger:"blur"
}
手动兜底校验
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert('submit!');
} else {
console.log('error submit!!');
return false;
}
});
},
清除内容及校验规则
resetForm(formName) {
this.$refs[formName].resetFields();
}
同时验证一块表单区域
都不填写触发校验时
填写两项触发的校验
全部填写后
<template>
<div>
<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
<el-form-item label="活动名称" prop="activity">
<div>
<el-input v-model="ruleForm.name" style="width: 100px" />
活动,将于
<el-date-picker
v-model="ruleForm.timeDate"
type="date"
placeholder="选择日期"
/>
请于
<el-time-select
v-model="ruleForm.time"
:picker-options="{
start: '08:30',
step: '00:15',
end: '18:30'
}"
placeholder="选择时间"
/>
到达现场
</div>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
<el-button @click="resetForm('ruleForm')">重置</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
export default {
data() {
const validatePass2 = (rule, value, callback) => {
const message = []
if (this.ruleForm.name === '') {
message.push('活动名称')
}
if (this.ruleForm.timeDate === '') {
message.push('活动日期')
}
if (this.ruleForm.time === '') {
message.push('到达时间')
}
if (message.length) {
const str = '请填写' + message.join('、')
callback(new Error(str))
} else {
callback()
}
}
return {
ruleForm: {
name: '',
timeDate: '',
time: ''
},
rules: {
activity: [
{ required: true, validator: validatePass2, trigger: 'blur' }
]
}
}
},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert('submit!')
} else {
console.log('error submit!!')
return false
}
})
},
resetForm(formName) {
this.$refs[formName].resetFields()
}
}
}
</script>
<style lang="scss" scoped>
</style>
多级校验 当数据是多层的时候校验
form:{
name:'',
role:{
name:''
}
}
1、给 el-form-item 的 prop=“” 设为:prop=“role.name”
2、然后在校验规则中:重点要用 ‘’ 括起来
rules: {
'role.name': [
{required: true, message: '请输入', trigger: 'blur'},
]
}