You should never, ever trust provided data submitted by users. Therefore, you should validate the request payload against some rules. Hapi streamlines this procedure and integrates a validation process for object schemas with the help of joi.
Joi is a robust validation plugin that validate objects against a predefined object schema.
Joi gives us an expressive way, to expect our data to look and an easy way to validate against those schema.
Every joi schema begins with a function being called from the object.
Simple Example Joi Schema
- object to validate
- Joi schema
The callback has passed two args an error and a validated value. As long as error is null your object it’s been validated, otherwise error will give you information on which validation step failed.
Complex object validation structures is not a problem for Joi to handle
Firstly you need to start with the object() function call on the joi object then, chain to that we will use keys function which defines a set of properties for that object in order to validate.
The keys function is a little different than the other chaining functions and usually takes a hash as the argument.
Each property on the hash is a property on your schema object to define.
The key name should much what you expect the validating object to contain, the value of each property is a
joi validation object just like the sting validation on the previous example.
If we had a username property we could validate it using the Joi.string function.
That we could chain to alphanum() function if we only expected names in the latin alphabet.
Then we can limit the length for the username.
Finally we can chain the required() function which ensures that this field has to be populated and validated by the user.
We can add another email property. Joi has a built in email validator which we can use by calling Joi.string() and chaining the email() function.
This email function allows fine tuned control, and again we can chain the required() function.
Those two validation properties defining our object schema joi will validate this example since both name and email are present and fit the schema criteria.
[alert type=white ]
I hope you enjoyed the tutorial if you have any problems please use the comment box below.
Happy coding 🙂
Also published on Medium.