Ant Design Vue is a powerful library since its components cover basically every use case. Specifically, its form component provides an intuitive API for building up the form, including form validation.
However, its form validation method only validates in the frontend. What if we want to display an error message generated by the backend?
Consider the following scenario, if a user wants 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 integrate 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 the component structure, we can observe that the form contains two fields. And an error was displayed in the first field.
The error message was controlled by
fields[i].validateState. Therefore, to make the form display custom error messages, we only need to change these two properties.
The response was defined in this way, the key is the field name, and the value is the error message.
The function first filters 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