Ant Design Vue is a powerful library since its components covers basically every use cases. Specifically, its form component provides an intuitive API for building up the form, including form validation.
However, its form validation method only validates in frontend. What if we want to display error message generated by backend?
Consider the following scenario, if a user want to update his or her email, only to find that the email has already been registered. A simple solution is to display an alert to notify the user. However, this can be achieved in a more elegant way. We can intergrate the error message with the form field error.
This tutorial uses Vue3.0 for example, however, the 2.x approach is similar to this, only with some small changes.
Given from the component structure, we can observed that the form contains two fields. And an error was displayed in the first field.
The error message was controlled by
fields[i].validateState. For making the form to display custom error message, therefore we only need to change these two properties.
The response was defined in this way, while the key is the field name, and the value are the error messages.
The function first filter out all the fields that are not mentioned in the error response. Then set their state to error and set the message to the first error message.
Tips for Ant Design Vue 1.x user
In 1.x, the
fields.name prop should be