element ui表单验证直接在字段上显示后台返回的错误信息

2021-06-10  本文已影响0人  码农梦醒
<template>
    <div class="hello">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="活动时间" required>
                <el-col :span="11">
                    <el-form-item prop="date1">
                        <el-date-picker type="daterange" placeholder="选择日期" v-model="ruleForm.date1"
                                        style="width: 100%;"
                                        range-separator="至"
                                        start-placeholder="开始日期"
                                        end-placeholder="结束日期"
                                        value-format="yyyy/MM/dd"
                        ></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col class="line" :span="2">-</el-col>
                <el-col :span="11">
                    <el-form-item prop="date2">
                        <el-time-picker placeholder="选择时间" v-model="ruleForm.date2"
                                        style="width: 100%;"></el-time-picker>
                    </el-form-item>
                </el-col>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
                <el-button @click="setErrorMsg('ruleForm')">给指定字段设置后台验证的错误信息</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
    export default {
        name: "HelloWorld",
        components: {},
        props: {
            msg: String
        },
        data() {
            return {
                ruleForm: {
                    date1: null,
                    date2: ''
                },
                rules: {
                    date1: [
                        {required: true, message: '请选择日期', trigger: 'change'}
                    ],
                    date2: [
                        {type: 'date', required: true, message: '请选择时间', trigger: 'change'}
                    ]
                }
            }
        },
        methods: {
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        alert('submit!');
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            setErrorMsg(formName) {
                console.log(this.$refs[formName].fields)
                this.$refs[formName].fields[0].validateState='error'
                this.$refs[formName].fields[0].validateMessage='后台错误信息'
            }
        }
    };
</script>

<style scoped lang="scss">
</style>
上一篇下一篇

猜你喜欢

热点阅读