AdonisJs 5- How to insert a validation to a Route like adonis v4? #1307
-
Hi, In AdonisJs 4, you can do something like this: Route.post("/myRoute", "myController.create").validator("randomValidator"); Can I do something something like that in version 5? and if not how can I use a validation created using:
Inside my Controller? |
Beta Was this translation helpful? Give feedback.
Answered by
thetutlage
Jul 23, 2020
Replies: 2 comments 2 replies
-
Here's in the doc https://preview.adonisjs.com/guides/http/form-submissions#using-validator-classes |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
dajpes
-
Hey, validations can be done on controllers through the request context App/Controllers/Http/UsersController.ts import StoreValidator from 'App/Validators/User/StoreValidator'
import UpdateValidator from 'App/Validators/User/UpdateValidator'
export default class UsersController {
public async store({ request }: HttpContextContract) {
const { name, password, isActive } = await request.validate(StoreValidator)
const user = await User.create({
name,
password: password,
isActive: isActive ?? true,
})
return user
}
public async update({ request, params }: HttpContextContract) {
const data = await request.validate(UpdateValidator)
const user = await User.findOrFail(params.id)
user.merge(data)
await user.save()
return user
}
} App/Validators/User/StoreValidator.ts import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { schema, rules } from '@ioc:Adonis/Core/Validator'
export default class StoreValidator {
constructor(private ctx: HttpContextContract) {}
public schema = schema.create({
name: schema.string({ escape: true, trim: true }, [rules.minLength(3)]),
password: schema.string({ escape: true, trim: true }, [rules.minLength(8), rules.confirmed()]),
isActive: schema.boolean.optional(),
})
public cacheKey = this.ctx.routeKey
public messages = {}
} |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's in the doc https://preview.adonisjs.com/guides/http/form-submissions#using-validator-classes