Display server-side validation error message in Ant Design Vue

Feb 5, 2023: Ant Design Vue has been in v3.x for a long time, so this post may be no longer valid. However, the idea in this post could still be drawn upon. For a real example of backend validation using Antdv 3.x and Inertia.js, please refer to my admin dashboard skeleton: Laravel Antd Pro. Feel free to contribute if you would like to.
Ant Design Vue
An enterprise-class UI components based on Ant Design and Vue
-

Ant Design Vue is a powerful library because its components cover virtually every use case. In particular, its form component provides an intuitive API for building 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: a user wants to update their email, only to find that the email has already been registered. A simple solution is to display an alert to inform the user. However, there is a more elegant way to do this. We can integrate the error message with the form field error.

This tutorial uses Vue3.0 as an example, but the approach for Vue 2.x is similar, with some minor 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].errors, fields[i].validateState. Therefore, to make the form display custom error messages, we only need to change these two properties.

Response Format

The response has been defined as follows, the key is the field name and the value is the error message.

{
  "status": "error",
  "error": {
    "name": [
      "The name contains sensitive word"
    ]
  }
}
Response data

Error handling

const displayError = function (errors) {
  ref.value.fields.filter(field => errors[field.name] !== undefined).forEach(field => {
    field.validateState = 'error'
    // set to first error message
    field.validateMessage = errors[field.name][0]
  })
}
Error handling function

The function first filters out any fields that are not mentioned in the error response. It then sets their state to error and sets the message to the first error message. The result were pictured below:

Display the error message from the backend

Tips for Ant Design Vue 1.x users

In 1.x, the fields.name prop should be fields.prop