AdonisJS: The proper way to handle Request Validation. Validation allows us to confirm the data we are working on and accept matches what we expect it to be.
So, we can use validation to confirm a requested username matches all of these criteria. As like, we can do this for all data we need to store for our app or application.
You can purchase your hosting from Cloudsurph.com, Cloudsurph hosting is a reliable hosting option for business and personal projects. We offer insight and help on system configuration issues and code errors or bugs.
The Adonis Validator
Nowadays every new Adonis project comes with the built-in Adonis Validator. The Adonis validator comes with a number of default types and rules that we can validate against.
So, we can also extend the rules as needed by defining ourselves. For any failed validations the validator provides error messages. It is also can be customized.
Basically, we can use the validator in two different contexts, directly off our request, and standalone. We will be focusing on The proper way to handle Request Validation first.
Adonis Validation Schema
We need to must first define a schema for the Validator to validate against. It will then use this schema to confirm all our data matches our schema definition. So, if any data fail our validation, the Validator will back an error.
You can check our previous article: AdonisJS: REST API simple CRUD Operation
If we start with we will want to import schema from @ioc:Adonis/Core/Validator.
So, this schema object is what contains our different types of definitions and a method to create our Validator schema.
IF you want then buy a good, reliable, secure web hosting service from here: click here
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext' import { schema, rules } from '@ioc:Adonis/Core/Validator' import Status from 'Contracts/Enums/Status' class TasksController { // ... other methods public async store ({}: HttpContextContract) { const taskSchema = schema.create({ name: schema.string(), description: schema.string.optional(), statusId: schema.enum(Object.values(Status)) }) } }
So now, here we need to create a new Validator schema by calling schema.create(). Our data may look something like this below:
{ name: "My Project Task", description: "Welcome to your new project task", statusId: 1 }
In this case, some types accept an argument of an array of rules and these rules, also exported from @ioc:Adonis/Core/Validator, and allow us to specify more granular validations wide and just validating the data type.
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext' import { schema, rules } from '@ioc:Adonis/Core/Validator'; import Status from 'Contracts/Enums/Status' class TasksController { // ... other methods public async store ({}: HttpContextContract) { const taskSchema = schema.create({ name: schema.string({}, [rules.minLength(3), rules.maxLength(50)]), description: schema.string.optional(), statusId: schema.enum(Object.values(Status)) }) } }
Adonis Validating Requests
The Validator lives in directly on our request object, and we can call the validate method by extracting our request from our HttpContextContract. Sao then, we provide it our schema.
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext' import { schema, rules } from '@ioc:Adonis/Core/Validator'; import Status from 'Contracts/Enums/Status' class TasksController { // ... other methods public async store ({ request }: HttpContextContract) { const taskSchema = schema.create({ name: schema.string({ trim: true }, [rules.minLength(3), rules.maxLength(50)]), description: schema.string.optional(), statusId: schema.enum(Object.values(Status)) }) const data = await request.validate({ schema: taskSchema }) } }
So, if our request body data is valid the validate method and we will return back an object containing only the keys that we defined on our schema. So, if our request body contained as like below:
{ name: " My Project Task ", description: "Welcome to your new project task", statusId: 1, assgineeId: 2 }
Adonis Custom Error Messages
The Adonis’ Validator allows us to define custom messaging for our validation fail. So, you can define error messages in a number of different ways.
Now, in order to apply these custom messages to our validation, we pass the object into our validate call, as like so.
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext' import { schema, rules } from '@ioc:Adonis/Core/Validator'; import Status from 'Contracts/Enums/Status' class TasksController { // ... other methods public async store ({ request }: HttpContextContract) { const taskSchema = schema.create({ name: schema.string({ trim: true }, [rules.minLength(3), rules.maxLength(50)]), description: schema.string.optional(), statusId: schema.enum(Object.values(Status)) }) const messages = { minLength: '{{ field }} must be at least {{ options.minLength }} characters long', maxLength: '{{ field }} cannot be longer than {{ options.maxLength }} characters long' } const data = await request.validate({ schema: taskSchema, messages }) } }
Finally, we just need to implement our rule and this was created with our username value in mind, and at the end let’s create a validation schema for our users.
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext' import { schema, rules } from '@ioc:Adonis/Core/Validator'; export default class UsersController { public async register({ request, response }: HttpContextContract) { const userSchema = schema.create({ username: schema.string({ trim: true }, [ rules.maxLength(50), rules.minLength(3), rules.unique({ table: 'users', column: 'username' }), rules.regex(/^[a-zA-Z0-9-_]+$/), rules.notIn(['admin', 'super', 'moderator', 'public', 'dev', 'alpha', 'mail']) // ]), email: schema.string({ trim: true }, [rules.unique({ table: 'users', column: 'email' })]), password: schema.string({}, [rules.minLength(8)]) }); const data = await request.validate({ schema: userSchema }) } }
That’s it. If you enjoyed reading this article and have more questions please reach out to our support team via live chat or email and we would be glad to help you. we provide server hosting for all types of need and we can even get your server up and running with the service of your choice.