el-form表单验证

一个表单,有很多个必填项,需求:这些必填项如果有一个有填其他的全变为不是必填项,如果都没有填,则都是必填项

export default {
    data () {
        return {
            dynamicValidateForm: {
                value: '',
                email: ''
            },
            rules: {
                email: [{ required: true, message: '请输入邮箱地址', trigger: 'blur' }],
                value: [{ required: true, message: '请输入正确的邮箱地址', trigger: 'blur' }]
            }
        }
    },
    watch: {
        dynamicValidateForm: {
            handler (val, oval) {
                console.log(val, oval)
                for (var  i  in  this.dynamicValidateForm) {
                    console.log(this.dynamicValidateForm[i])
                    if (i) {
                        this.rules[i][0].required  =  true
                    } if (!i) {
                        this.rules[i][0].required  =  false
                    }
                },
                deep:  true
            }
        }
    },

    methods: {
        submitForm (formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    alert('submit!')
                } else {
                    console.log('error submit!!')
                    return  false
                }
            })
        }
    }
}

请问一下watch里该怎么写,给出感谢

阅读 1.8k
1 个回答

大概这样写:

const checkValidator = (msg) => (rule, value, callback) => {
  if (!this.form.email && !this.form.value) {
    callback(new Error(msg));
  } else {
    this.$refs.form.clearValidate(["email", "value"]);
    callback();
  }
};

{
     rules: {
        email: [{ validator: checkValidator('请输入邮箱地址'), trigger: 'blur' }],
        value: [{ validator: checkValidator('xxxxx'), trigger:'blur' }]
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题