I have used Ant design's form component with v-decorators
for validating forms and I want to display client side(v-decorator rule validation which I have done currently) as well as server side form data validations.
Consider this as a sample login form:
<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>
I've submitted the form data to a laravel server, and I'll eventually get some validation errors that I need to display into the ant's form. My validation error object looks like this:
{
errors: {
email: "The email must be a valid email address.",
password: "(some validation message here)"
}
}
I don't want to loose the ant's form validation functionality and I also want to show server side validation errors along with it. Is there any way to achieve this in vue?
You can use setFields
method of form to set error state.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With