Element UI 为我们提供了表单校验规则,但业务需要,我们常常要自定义校验规则
需求
实现表单中一个输入框,不能输入大于30的数字
思路
hrml:
自定义校验规则:
约定的校验规则:
代码
<template>
<div id="app" class="container">
<el-form ref="form" :model="form" :rules="rules" label-width="80px">
<el-form-item label="Number" prop="Number">
<el-input v-model="form.Number"></el-input>
</el-form-item>
</el-form>
<el-button @click="submit">Save</el-button>
</div>
</template>
<script>
export default {
name: 'App',
components: {
// UploadPhoto
},
data() {
const myValidate = (rule, value, callback) => {
if(value > 30){
callback(new Error('输入不能大于30'))
}
callback();
}
return {
form: {
Number: 2,
},
// 表单校验
rules: {
Number: [{required: true}, { validator: myValidate }]
}
}
},
created() {
//
},
methods: {
submit() {
this.$refs['form'].validate((valid) => {
if (valid) {
alert('submit!');
} else {
console.log('error submit!!');
return false;
}
});
}
}
}
</script>
<style>
.el-input {
width: 200px !important;
}
</style>