Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I validate "number of digits" from joi using nodejs?

i want that if the number of digits in the input field in less/more than 14(for example) then joi should return an error.

how can i do this with the type of number not for string.

like image 914
Ravi Singh Avatar asked Sep 18 '19 12:09

Ravi Singh


People also ask

How do I validate a number in Joi?

Joi validate numbersconst schema = Joi. object(). keys({ age: Joi. number().

How do I validate a number in node JS?

You will need to convert the Buffer to String using toString() method. Once you have the String , you can try to parse the string to a number (Int or Float) using methods of Number class ( Number. parseInt or Number.

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.


2 Answers

Validation for 10 digit numeric mobile number are given below

joi.string().length(10).pattern(/^[0-9]+$/).required(),

You should change the rule as per your requirement. pattern(your regex) is used to accept only digits, length() is used to validate how many character validation accepts and only work with string function.

like image 128
waseem asgar Avatar answered Oct 10 '22 18:10

waseem asgar


Validation for 10 digit numeric mobile number with custom error message are given below

joi.string().regex(/^[0-9]{10}$/).messages({'string.pattern.base': `Phone number must have 10 digits.`}).required()
like image 34
Manoj Rana Avatar answered Oct 10 '22 18:10

Manoj Rana