How to validate out of the controller (v5)

I would like to create a file on the route App/Validators/UserValidator.ts.
Inside it I define the schema with the schema.create.

Now how do I call this validation through the controller / routes?

In adonis v4.1, it was only necessary to add the call as route.get('route', 'controller').validator('UserValidator') in the routes.

Note: I`m using adonis v5.

WIth Validation in Adonis5, the validation is done in the Controller, even though your rules can be in a separate Validator class(file)

Using your above example, you have to do it as follows

import UserValidator from 'App/Validators/UserValidator'

//then within your controller method

public async store ({request, response} : HttpContextContract) {
        const data = await request.validate(UserValidator)
// the above one liner will handle validation

See link here
I hope this helps

1 Like