Home > Mobile >  Adonis not showing custom error for Route Validator
Adonis not showing custom error for Route Validator

Time:11-01

I have the following route:

  Route.resource("veiculos", "VeiculoController").validator(
    new Map([[["veiculos.store"], ["StoreVeiculo"]]])
  );

and my validator file looks like this:

'use strict'

class StoreVeiculo {
  get rules () {
    return {
      vei_placa: 'required',
    };
  }

  get messages () {
    return {
      'required':  'Placa do veiculo nao foi enviada',
    };
  }
  
}

module.exports = StoreVeiculo

I'm expecting to receive this error message: "Placa do veiculo nao foi enviada" but I'm receiving the default "Validation failed. Make sure you have filled all fields correctly" instead.

Yes I'm sending a POST request to /veiculos endpoint.

P.S: I'm using adonis v4 and followed the steps here: https://legacy.adonisjs.com/docs/4.1/validator#_route_validator

CodePudding user response:

I found the answer, I needed to add an async method called fails to my Validator class:

  async fails(errorMessages) {
    return this.ctx.response.status(400).send(errorMessages[0].message);
  }

This will ensure that the customer message I defined on get messages() will be returned.

According to my tests, it doesn't display all errors you might have in your request for once.

My Final validator class looks like this:

'use strict'

class StoreVeiculo {
  get rules () {
    return {
      vei_placa: 'required',
    };
  }

  get messages () {
    return {
      'required':  'Placa do veiculo nao foi enviada',
    };
  }

  async fails(errorMessages) {
    return this.ctx.response.status(400).send(errorMessages[0].message);
  }
  
}

module.exports = StoreVeiculo
  • Related