Custom error messages for route validation not working


#1

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',
      'email.email': '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 Route.post('users', 'UserController.store').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


#2

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


#3

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?


#4

Use middlewares to achieve that.


#5

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?


#6

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.


#7

Works fine. Thanks


#8

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!