Object Validation With Joi In React Js & Node Js

In this blog, we will see how to use Joi library for object and arrays validation. Object validation is very important on the front-end side to restrict users from entering valid data and also important on the back-end side to verifying what goes into our REST API won’t break our code.

What Is Joi?

Joi is the powerful npm library to validate the JavaScript object when we need to perform these checks, like validating response from a backend endpoint. First, let’s see the available libraries for validating the JavaScript object. Below is the list of some popular libraries for object validation features:

1.  ajv

2. express-validator

3. nope-validator

4. decoders

5. swagger-parser

Implementation Steps Of Joi

Let’s see how to use Joi to validate javascript objects step by step in the Express application.

1. Define package.json file:

First, create a project folder and define package.json file init for that; write the below command.

npm init -y

2. Installations:

First, create the express application and Install the Joi library. Next, you need to write the below line in your terminal.

npm install Joi

3. Creating Schema:

After successful installation, you must import Joi and create the schema for the object we need to validate. In the schema, we set up some rules specific to each value in the object. Let’s see how to create a schema.

const Joi = require('Joi');

//Joi schema to validate the object data
const schema = Joi.object().keys({ 
  name: Joi.string().alphanum().min(3).max(30).required(),
  email: Joi.string().email()
}); 
const dataToValidate = { 
  Name: “John”, 
  email: “john@domain.com”
} 

const result = Joi.validate(dataToValidate, schema); 
// result.error == null means valid

In the above code, we have created a schema for our API payload where we have two fields. And we are validating both of the fields with the help of Joi.

Here, what we are doing is two things:

First, we are constructing a schema for that we are using Joi. object() method, and then we are validation our data object using Joi. validate() method.

If our data is valid, then Joi. validate(schema, dataToValidate) will return null otherwise, it will return the error object and based on the return value, we can send the status of the API.

4. Constructor Support:

We can validate the data for all the primitives as we as regex. And we can also be nested to any depth. Let’s see some basic constructors that we can use to validate the data with Joi.

  • string: This says that value must be string, and we use it like this Joi.string()
  • number: This says that value must be number. Joi.number() is also supports helper operations such as min() and max(), like this Joi.number().min(1).max(10)
  • required: This says that property is required, like this Joi.string().required()
  • any: This says that the property could be any type, usually we tend to use it with the helper allow() that specifies what it can contain, like this, Joi.any().allow(‘a’)
  • optional: The optional not validate the type but after applying the other validation we can use it if that property is not mandatory like this, Joi.string().optional this means if the value is not provided then there is no problem but if it provided and the primitive is an integer or any value other than string the validation will fail.
  • array: This says that the property is must be array, and we use it like this Joi.array().items(Joi.string().valid(‘a’, ‘b’))
  • regex: It supports pattern matching with RegEx as well like this Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/)

I suggest you to have a look into the Joi API where you can find all the methods that we can use for validation.

5. Validating Nested Object:

So we have only shown how to create schema so far that is one level deep. Now let’s see how to create the nested schema.

const personalData = Joi.object().keys({ 
  name: Joi.string().alphanum().min(3).max(30).required(),
  email: Joi.string().required(), 
  address: Joi.object.keys({ 
   country: Joi.string().required(), 
   state: Joi.string().required(), 
   city: Joi.string().required(),
   zip_code: Joi.number().required()
  })) 
});

Here we have a nested schema. The address schema looks exactly like the outer call we first make. Nesting is as easy as that.

6. Joi As A Middleware:

We can use Joi as middleware and use it every time we need validation. With this approach, we can eliminate extra code in every API for validation. For creating middleware, first, create a middleware folder in the project directory, and in that folder, create validationMiddleWare.js. In this file, add write below code.

exports.validate = (schema) => (req, res, next) => {
  const {
   error
  } = schema.validate(req.body);
  if (error) {
    res.status(422)
      .send(error.details[0].message);
  } else {
    next();
  }
};

It will receive a schema and check our req.body against the schema.

Now, create a file called validation.js. This will hold our schemas. Paste the following code into it.

const Joi = require("joi");

exports.person = Joi.object()
  .keys({
    name: Joi.string()
      .min(3)
      .max(40)
      .required(),
    age: Joi.number()
      .integer()
      .min(16)
  });

Now create an API like so, after importing both files.

const validation = require('./validation')

const {

  validate

} = require('./validationMiddleware')

app.post("/", validate(validation.person), (req, res) => {

  res.send("request processed");

});

const validation = require('./validation')
const {
  validate
} = require('./validationMiddleware')

app.post("/", validate(validation.person), (req, res) => {
  res.send("request processed");
});

Advantages Of Object Validation With Joi In React Js & Node Js

  • Easy to implement and easy to learn.
  • Widely accepted and well-known package for data validation.
  • Supports validation based on the schema.
coma

Conclusion

In this blog, we saw how to validate objects and arrays with the help of Joi and what schema is, constructor support while creating a schema and how to validate the data. Then, at last, we saw the advantages of using Joi. Thank you for reading! In case you have any questions, feel free to comment.

Nadeem

Frontend Developer

Nadeem is a Front-end developer with 1+ year of experience. He has experience in web technologies like ReactJS, Redux and UI Frameworks. His expertise in building interactive and responsive web applications, creating reusable components and writing efficient, optimized and DRY code. He enjoys learning about new technologies.

Get in touch for a detailed discussion.

Hear From Our 100+ Customers
coma

Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.

author
ADDIE WOOTTEN
CEO, SMILINGMIND
coma

We had very close go live timeline and MindBowser team got us live a month before.

author
Shaz Khan
CEO, BuyNow WorldWide
coma

They were a very responsive team! Extremely easy to communicate and work with!

author
Kristen M.
Founder & CEO, TotTech
coma

We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.

author
Chacko Thomas
Co-Founder, TEAM8s
coma

Mindbowser is one of the reasons that our app is successful. These guys have been a great team.

author
Dave Dubier
Founder & CEO, MangoMirror
coma

Mindbowser was very helpful with explaining the development process and started quickly on the project.

author
Hieu Le
Executive Director of Product Development, Innovation Lab
coma

The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.

author
Alex Gobel
Co-Founder, Vesica
coma

Mindbowser is professional, efficient and thorough. 

author
MacKenzie R
Consultant at XPRIZE
coma

Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.

author
Laurie Mastrogiani
Founder, S.T.A.R.S of Wellness
coma

MindBowser was great; they listened to us a lot and helped us hone in on the actual idea of the app.” “They had put together fantastic wireframes for us.

author
Bennet Gillogly
Co-Founder, Flat Earth
coma

They're very tech-savvy, yet humble.

author
Uma Nidmarty
CEO, GS Advisorate, Inc.
coma

Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.

author
Katie Taylor
Founder, Child Life On Call
coma

As a founder of a budding start-up, it has been a great experience working with Mindbower Inc under Ayush's leadership for our online digital platform design and development activity.

author
Radhika Kotwal
Founder of Courtyardly
coma

The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!

author
Michael Wright
Chief Executive Officer, SDOH2Health LLC
coma

They are focused, patient and; they are innovative. Please give them a shot if you are looking for someone to partner with, you can go along with Mindbowser.

author
David Cain
CEO, thirty2give
coma

We are a small non-profit on a budget and they were able to deliver their work at our prescribed budgets. Their team always met their objectives and I'm very happy with the end result. Thank you, Mindbowser team!!

author
Bart Mendel
Founder, Mindworks
coma

Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.

author
George Hodulik
CEO, Stealth Startup, Ex-Google