Display validation error message by backend in Ant Design Vue

Frontend May 13, 2021
Ant Design Vue
An enterprise-class UI components based on Ant Design and Vue

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].errors, fields[i].validateState. Therefore, to make the form display custom error messages, we only need to change these two properties.

Response Format

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

The response was defined in this way, the key is the field name, and the value is the error message.

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 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.

Display the error message from the backend

Tips for Ant Design Vue 1.x user

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

Tags

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.