为什么 element-ui 的 validate() 函数不断清除服务器端通过验证(通过错误道具)错误?



我正在使用元素 ui 表单验证来验证客户端的简单规则,以减轻服务器的额外负载。初始客户端验证通过后,我将它们发送到服务器并在服务器端执行更多(复杂)验证。

当我收到返回的错误并将其显示在自定义构建的错误字段中时,这没有任何问题。但是,当尝试使用element-ui的内置错误道具来显示表单项中的错误时,在第二次提交后,服务器端错误将从表单项中消失。即使我像error="This is a error message"这样对错误道具进行硬编码,运行 validate() 方法后消息仍然消失。

这是表单的示例

<el-form :model="form" :rules="rules" ref="form">
<el-form-item prop="mobile_number" :error="errors.mobile_number[0]">
<el-input v-model.number="form.mobile_number"> </el-input>
</el-form-item>
</el-form>

这是我提交表格的部分

submitForm(){
this.$refs.form.validate((valid) => {
if (valid) {
axios.post(url, 
this.form
).then((response) => {
if(response.data.status == 'success'){
// do stuff when successful
}
}).catch((error) => {
this.errors = error.response.data.errors;
})
}
});
}

当我删除 validate() 方法或禁用客户端的验证规则时,服务器端仍然存在。如何解决此问题?

在查看了源代码之后,这就是我发现的。元素 ui 验证对内部进程和外部 prop 错误使用相同的错误消息变量 (validateMessage)。 因此,当 validate() 运行时,element-ui 首先检查它自己的规则,如果它通过,则返回有效的 true,否则它会创建错误并将它们分配给 validateMessage。

另一方面,传递手动错误元素 ui 是使用监视错误道具的观察程序。

watch: {
error: {
immediate: true,
handler: function handler(value) {
this.validateMessage = value;
this.validateState = value ? 'error' : '';
}
},
validateStatus: function validateStatus(value) {
this.validateState = value;
}

},

因此,为了控制分配给 validateMessage 的内容,需要触发观察者,这只有在错误 prop 发生变化时才能触发,只要它保持不变,内部验证过程就会覆盖 validateMessage。

validator.validate(model, { firstFields: true }, function (errors, invalidFields) {
_this.validateState = !errors ? 'success' : 'error';
_this.validateMessage = errors ? errors[0].message : '';
callback(_this.validateMessage, invalidFields);
_this.elForm && _this.elForm.$emit('validate', _this.prop, !errors, _this.validateMessage || null);
});

就我而言,由于客户端验证通过规则 validateMessage 设置为",因此即使服务器端仍然保持错误,也不会显示任何错误。

简而言之,当元素服务器端验证器通过有效时,我会在提交表单之前清除本地错误。如果存在,让它再次设置它们。它有效。

submitForm(){
this.$refs.form.validate((valid) => {
if (valid) {
this.errors = [];
axios.post(url, 
this.form
).then((response) => {
if(response.data.status == 'success'){
// do stuff when successful
}
}).catch((error) => {
this.errors = error.response.data.errors;
})
}
});
}

最新更新