Need data validation? Check out Joi – it will be useful!

Let me briefly describe how it works: coding with the use of this tool can be briefly divided into a few steps. The first is to prepare a schema, which is an object that describes the expectations regarding the entered data. Then, the data that we want to test for compliance with the prepared schema should be provided. The data will be validated and the result will be returned.

See also: RPA in real estate: How to leverage automation?

The extensive documentation is a huge support when working on the schema, I also refer to it. Later in the article I will focus only on validation, where we are dealing with dependencies between validated data. I will take the described cases from my own experience.

Making the presence of one key dependent on another is not a problem. It is enough to use the functionality provided by the “when()” method, for example:

 

Joi.object({

 oneKey: Joi.boolean().optional(),

 anotherKey: Joi.string()

   .when(‘oneKey’, {

     is: Joi.exist().valid(true),

     then: Joi.required(),

     otherwise: Joi.optional()

   })

});

 

However, this solution is not sufficient if we would like to make the presence of two keys dependent on each other. Geographic coordinates are a good example here. Suppose entering them is optional, but we want the latitude to be required if the longitude is specified, and vice versa. When we try to use the mentioned “when()” method, we will get an exception informing us that we have defined an unacceptable dependency. The solution is to use the “and()” method as seen in the code snippet below. Additionally, I used the “options()” method to avoid duplicating the “optional()” method call in the code.

 

Joi.object({

 latitude: Joi.number(),

 longitude: Joi.number(),

})

 .and(‘latitude’, ‘longitude’)

 .options({

   presence: ‘optional’,

 });

 

By the way of the “and()” method, it is worth mentioning the “nand()” method. It defines a dependency where not all the keys in the list can be defined. The “o ()” and “xor()” methods are also noteworthy. Both allow us to define a list of keys, one of which is required. For “xor()” as opposed to “or()”, only one key from the list is allowed. Complementing this set is the “orox()” method, which allows us to specify that only one of the key lists is acceptable but all of them are optional, so you can not define any of them.

Sometimes it is necessary to limit the value assigned to one key from the value of another key. In my opinion, time frames are a good example here. Let’s assume that the user can filter the returned data by indicating a time interval. Additionally, the scope cannot exceed one calendar year. The “ref()” method, which generates a reference to the value associated with the selected key, is helpful in this case. After obtaining the reference, we can implement our own logic, which can be seen in the example below:

 

Joi.object({

 from: Joi.date().iso(),

 to: Joi.date()

   .iso()

   .min(

     Joi.ref(‘from’, {

       adjust: (value) => new Date(value),

     }),

   )

   .max(

     Joi.ref(‘from’, {

       adjust: (value) => {

         const date = new Date(value);

         return new Date(

           date.getFullYear() + 1,

           date.getMonth(),

           date.getDate(),

         );

       },

     }),

   ),

}).options({

 presence: ‘required’,

});

 

Joi is one of the many libraries that help you validate your input. It won my favor due to the wide range of possibilities it offers when it comes to data verification, and it is not the first one that I had the opportunity to use. I am aware that each of these libraries will find its supporters and opponents. However, I hope that I was able to clearly present some of the advantages of the Joi library.

You may like to read:
React Hooks – revolutionary changes in React
React Native vs Swift (native iOS) – clash of the titans
Swift vs Objective-C: Which language should you choose for your project?
Different software test types and everything you should know about them
GraphQL, Hyperledger Fabric & Go – what you need to know?
Code reusability vs. programming principles
What is technical debt? Here’s what you need to know!
Code cleaning – is it worth the time spent on it?
What is Kubernetes? Here’s what you need to know

Full Stack Web Developer in Concise Software who follows new programming trends and focused on self-development. Husband and father, passionate about mountain trips.

You don't have permission to register