Custom validators

Hi all,

There is actually a pretty easy way to accomplish this in Strapi 4,

The Forms use Yup validation so you can hack into that system to prompt a custom error message on the input itself and also show a global error message while you’re at it.

Just create a lifecycles.js file inside the content-types folder, here is some example code to help you get started

  async beforeUpdate(event) {
    const { data } = event.params;
    const { YupValidationError } = require("@strapi/utils").errors;

    if (data.description) {
      const errorMessage = {
            "inner": [
                {
                    "name": "ValidationError", // Always set to ValidationError
                    "path": 'description', // Name of field we want to show input validation on
                    "message": 'some custom error message', // Input validation message
                }
            ]
        };
      const globalErrorMessage = "You have some issues";
      throw new YupValidationError(errorMessage, globalErrorMessage);
    }

  },```

more info at [Strapi lifecycle hooks docs](https://docs.strapi.io/developer-docs/latest/development/backend-customization/models.html#lifecycle-hooks)
3 Likes