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);
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.
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.
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.
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.
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 });
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With