Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate string with Joi?

Tags:

node.js

joi

I am using Node Joi for validation. I am new in node I want to validate env to accept only 2 words "Yes" or "No" What changes I have to make in the following code

schema = Joi.object().keys({
    app_id: Joi.string().required(),
    env: Joi.string().required()
});
like image 822
Farhan Yaseen Avatar asked Sep 21 '16 07:09

Farhan Yaseen


People also ask

What is Joi validation?

Hapi Joi is an object schema description language and validator for JavaScript objects. With Hapi Joi, we create blueprints or schemas for JavaScript objects (an object that stores information) to ensure validation of key information.

Should I use Joi or express validator?

Joi can be used for creating schemas (just like we use mongoose for creating NoSQL schemas) and you can use it with plain Javascript objects. It's like a plug n play library and is easy to use. On the other hand, express-validator uses validator. js to validate expressjs routes, and it's mainly built for express.

What is the use of joi in Nodejs?

Joi module is a popular module for data validation. This module validates the data based on schemas. There are various functions like optional(), required(), min(), max(), etc which make it easy to use and a user-friendly module for validating the data.


1 Answers

You can use valid function to define valid values for the field:

schema = Joi.object().keys({
    app_id: Joi.string().required(),
    env: Joi.string().valid("Yes", "No").required()
});
like image 139
Vsevolod Goloviznin Avatar answered Sep 30 '22 10:09

Vsevolod Goloviznin