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 K

Associate Software Engineer

Nadeem is a front-end developer with 1.5+ years of experience. He has experience in web technologies like React.js, 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.

Keep Reading

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?