#JoiForFormValidation

Melike Kilic
2 min readSep 14, 2020

Forms had been the least pleasant thing to build in a project for me, back when I was a student at Flatiron School, and my mind hasn’t changed since then. Though, I got to accept the fact that it was hard to avoid them in my projects, especially when there’s a login/signup kind of thing going on.

Making peace with forms wasn’t enough; I needed a way to validate the data coming through the forms. (Remember, no external data is trustworthy unless validated!)

There Joi was smiling at the corner, waiting to be implemented in my form validation.

Photo by Belinda Fewings on Unsplash

Being a data validator, Joi is a library that lets you write and apply a schema in your projects to provide a proper structure that your objects must follow.

Joi, initially, is a server-side schema description language, but this will be a mini tutorial for joi-browser instead, which is the client-side version of Joi.

Set-Up

  1. Install the library the classic way:
npm install joi-browser

2. Import Joi into your form validation file:

import Joi from "joi-browser"

Implementation

Joi has two main parts:
1. The schema

2. The validation

Let’s start defining the schema based on your expectation of what your object should include:

(for this example, the form will consist of username, email, password, repeat the password)

schema = {
username: Joi.string()
.required()
.alphanum()
.min(8)
.max(25)
,
password: Joi.string()
.required()
.pattern(new RegExp("^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$")),
repeat_password: Joi.ref('password'),email: Joi.string()
.email({ minDomainSegments: 2, tlds: { allow: ['com'] }
.with('password', 'repeat_password');

The above code says that

the username must

  • be a required string
  • include not more than 25 characters but at least eight characters
  • consist of alphanumerical characters

the password must

  • be a required string
  • match the regex pattern stated
  • be equal to the repeat_password

the email must

  • be a string
  • include two parts of a domain
  • have the top-level domain as ‘.com’

Now that you have the schema, you need the second part of the implementation, which is in charge of validating the data. You can do this:

const result = schema.validate(input)

This should return value and error.

If there’s an error, it will let you know about that.

If not, the value will be your input.

That was it for this week’s blog post. Remember to bring Joi to your life by incorporating it into your projects!

--

--