Custom error messages for route validation not working


I have a StoreUser route validator like below:

'use strict'

class StoreUser {

  get validateAll () {
    return true

  get rules () {
    return {
      email: 'required|email|unique:users',
      username: 'required|unique:users',
      password: 'required',
      phone: 'required|integer'

  get messages () {
    return {
      'email.required': 'email address is required',
      '': 'please enter a valid email address',
      'email.unique': 'a user with this email already exists',
      'username.required': 'username is required',
      'username.unique': 'a user with this email already exists',
      'phone.required': 'phone number is required',
      'phone.integer': 'only integers are allowed as phone number',

module.exports = StoreUser

and I’ve added the validator to my route like this'users', '').validator('StoreUser') but instead of getting the custom error messages I defined, I’m getting Validation failed. Make sure you have filled all fields correctly. Anyone know why this is happening?

cc: @virk


If you are building the JSON API, then please set Accept header when making the request to the server.

Accept: application/json

Adonis internals heavily relies on content negotiation to format the correct response. When accept header is missing, then as per validator, the client want to accept the raw text and not the JSON


Makes sense and it works but is there any way to set it up internally so the client doesn’t have to send Accept: application/json on every request?


Use middlewares to achieve that.


Thanks for your response. I created a global middleware to handle this but I’m having issues setting the Header. I’m currently doing this but it’s not working:

class ContentType {
  async handle ({ request, response }, next) {
    request.header('Accept', 'application/json')
    await next()

What’s the correct way to do this?


Try like that :

async handle ({ request }, next) {
  let headers = request.headers()
  headers.accept = 'application/json'

  await next()

I don’t think there’s method(s) to deal with request headers.


Works fine. Thanks


You can also extend Request object by adding setHeader(name: string, value: string) method. More info here : Request
This way, all what you have to do is :

async handle ({ request }, next) {
  request.setHeader('Accept', 'application/json')

  await next()

and you’re done!