AdonisJS: simple user registration and authentication setup. AdonisJS provides a few different approaches to validate your request form data.
The proper way to handle Request Validation
We will use the Validation continually, we can either use it inside the controller’s method or create a Validator class to validate the incoming requests.
So, in this article, we will provide how to use the validations properly. And we will create an API for the user registration form.
Installation
Firstly, we create a new AdonisJS project using the npm package manager.
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.
npm init adonis-ts-app@latest hello-world
We already published an article for CRUD in AdonisJS, so you can read first our previous article on How to set up CRUD in AdonisJS.
Controller
Secondly, we create a controller and add a register method for user authentication.
node ace make:controller User
The controller will be created at app/Controllers/Http/UsersController.ts
And add the register method inside the app controller
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext' export default class UsersController { /** * * Other methods ... * **/ public async register({ request }: HttpContextContract) { } }
Validator
So, now we can create a validator class and define its parameters
node ace make:validator RegisterUser
In this case, the validator class will be created at app/Validators/RegisterUserValidator.ts and it will look like as below:
import { schema, CustomMessages, rules } from "@ioc:Adonis/Core/Validator"; import type { HttpContextContract } from "@ioc:Adonis/Core/HttpContext"; export default class RegisterUserValidator { constructor(protected ctx: HttpContextContract) {} public schema = schema.create({}); public messages: CustomMessages = {}; }
constructor: method accept HTTP context variable
scheme used to define parameter rules
messages: used to define our custom messages
IF you want then buy a good, reliable, secure web hosting service from here: click here
Now we need to add the rules:
public schema = schema.create({ name: schema.string({ trim: true }), email: schema.string([ rules.email(), rules.unique({ table: "users", column: "email" }), ]), password: schema.string([rules.minLength(6)]), });
To access the full list of rules go to the official AdonisJS documentation
Next, we can add our custom messages to the defined rules and you can leave them empty as well and AdonisJS will print default messages
public messages = { "name.required": "Name is required", "email.required": "Email is required", "email.email": "Email is invalid", "email.unique": "Email already exists", "password.required": "Password is required", "password.minLength": "Password must be at least 6 characters", };
Finally, our validator class will look like this below:
import { schema, CustomMessages, rules } from "@ioc:Adonis/Core/Validator"; import type { HttpContextContract } from "@ioc:Adonis/Core/HttpContext"; export default class RegisterUserValidator { constructor(protected ctx: HttpContextContract) {} public schema = schema.create({ name: schema.string({ trim: true }), email: schema.string([ rules.email(), rules.unique({ table: "users", column: "email" }), ]), password: schema.string([rules.minLength(6)]), }); public messages = { "name.required": "Name is required", "email.required": "Email is required", "email.email": "Email is invalid", "email.unique": "Email already exists", "password.required": "Password is required", "password.minLength": "Password must be at least 6 characters", }; }
Back to Controller
Now, we will use the defined validator class inside our app controller
public async register({ request, response }: HttpContextContract) { // Payload returns the validated data const payload = await request.validate(RegisterUserValidator); const user = await User.create(payload); return response.json(user); }
And finally, we will define the routes for register
Route.post("/register", "UsersController.register");
All are done!!!
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.