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 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].errors, fields[i].validateState. For making the form to display custom error message, therefore 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, while the key is the field name, and the value are the error messages.

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

Display the error message from backend

Tips for Ant Design Vue 1.x user

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

Tags

Stanley Tsau

Email: [email protected]tanleytsau.me

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.