Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate the length of character is equals to 5 using express-validator?

I am planning to make partnerid field character length as 5 which means user will get error message if he enters less than 5 character or more than 5 characters which will include alpha-numeric character. How can we do it using express-validator? I tried using below code but it didn't worked Thanks

   req.checkBody('partnerid', 'Partnerid field must be 5 character long ').len(5);
like image 305
Bibek Avatar asked May 18 '18 06:05

Bibek


People also ask

What is not () in Express validator?

notEmpty() adds a validator to check if a value is not empty; that is, a string with a length of 1 or bigger. https://express-validator.github.io/docs/validation-chain-api.html#notempty. Follow this answer to receive notifications.

What is checkFalsy in Express validator?

You can customize this behavior by passing an object with the following options: nullable: if true, fields with null values will be considered optional. checkFalsy: if true, fields with falsy values (eg "", 0, false, null) will also be considered optional.

How does express validator work?

According to the official website, Express Validator is a set of Express. js middleware that wraps validator. js , a library that provides validator and sanitizer functions. Simply said, Express Validator is an Express middleware library that you can incorporate in your apps for server-side data validation.

How do I validate a number in node js?

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. parseFloat ). You can then check if the number you parsed was a valid number or not using Number.


2 Answers

You can use isLength() option of the express-validator to check max and min length of 5:

 req.checkBody('partnerid', 'Partnerid field must be 5 character long ').isLength({ min: 5, max:5 });
like image 188
Ankit Agarwal Avatar answered Oct 10 '22 21:10

Ankit Agarwal


You can use matches option of express-validator to check if the partner field only contains alphanumeric and has a length of 5

req.checkBody('partnerid', 'Partnerid field must be 5 character long ').matches(/^[a-zA-Z0-9]{5}$/, "i");
like image 30
sachin.ph Avatar answered Oct 10 '22 20:10

sachin.ph