(VUE)Ant Design使用v-Decorator以Ant的形式显示客户端和服务器端的验证
我已将Ant Design的Form组件与v-decorators
一起用于验证表单,我希望显示客户端(我目前已完成的v修饰符规则验证)和服务器端表单数据验证。
将其视为示例登录表单:
<template>
<AForm
:form="form"
@submit.prevent="handleSubmit"
>
<FormItem>
<AInput
v-decorator="['email', { rules: [{ required: true, message: 'Please input your email!' }] }]"
placeholder="Email"
/>
</FormItem>
<FormItem>
<AInput
v-decorator="['password', { rules: [{ required: true, message: 'Please input your Password!' }] }]"
placeholder="Password"
type="password"
/>
</FormItem>
<FormItem>
<AButton
html-type="submit"
class="w-full"
:loading="loading"
>
Log in
</AButton>
</FormItem>
</AForm>
</template>
<script>
import { Form, Input, Button } from 'ant-design-vue';
import { mapActions } from 'vuex';
export default {
components: {
AForm: Form,
FormItem: Form.Item,
AInput: Input,
AButton: Button,
},
data() {
return {
form: this.$form.createForm(this),
errors: {},
loading: false,
};
},
methods: {
...mapActions(['login']),
handleSubmit() {
this.errors = {};
this.form.validateFields((err, values) => {
if (!err) {
this.loading = true;
this.login(values)
.then(() => {
this.$router.push('/');
})
.catch(({ response = {}, message }) => {
const { errors } = response.data;
if (errors) {
this.errors = errors; // I want to display these errors
return;
}
this.$notify.error(message || 'Unable to login');
})
.finally(() => {
this.loading = false;
});
}
});
},
},
};
</script>
我已经将表单数据提交给了LALAVEL服务器,我最终会得到一些需要显示在Ant的表单中的验证错误。我的验证错误对象如下所示:
{
errors: {
email: "The email must be a valid email address.",
password: "(some validation message here)"
}
}
我不想失去Ant的表单验证功能,我还想显示服务器端的验证错误。有什么方法可以真正做到这一点吗?
解决方案
可以使用Form的setFields
方法设置错误状态。
this.login(values)
.then(() => {
this.$router.push('/');
})
.catch(({
response = {},
message
}) => {
const {
errors
} = response.data;
if (errors) {
this.form.setFields({
'email': {
errors: [{
"message": errors.email,
"field": "email"
}]
},
'password': {
errors: [{
"message": errors.password,
"field": "password"
}]
}
});
return;
}
相关文章