express-validator-helper
Simple express-validator wrapper for easier work with validation error handling.
Installation
$ npm i express-validation-helper -S
// add expressValidator before helperapp;app;
Usage
Just do a check with express-validator as usual. Then instead req.validationErrors(true)
call req.validate()
. This method returns a Validator
object.
Validator object
add(fieldName, msg)
Add error with msg
to fieldName
.
isValid()
Returns true
if all data is valid. Otherwise false
.
errors
Object with all validation errors. It should be used only if the isValid
method returns false
.
Values contain an array with a list of errors. Example:
email: 'required' 'invalid format' 'already taken' password: 'required'
Customization
You can pass name
option to middleware with a custom method name:
app
Before & After
Confirmation handler example.
Before
exports { // checks with reverse order req; req; var errors = req; var email = reqbodyemail; return User;};
After
exports { // checks with normal order req; req; // call validate method on `req` object var validator = req; var email = reqbodyemail; return User;};
Reason
express-validator (Validator.js middleware for Express.js) is wonderful tool for validating user input. But it does not allow to define custom async validators. For example we want to check if email is already taken on signup page. Ok, we can add errors manually to req.validationErrors()
result. And here we are faced with several problems:
req.validationErrors()
result
express-validator provides two ways to get a result - as an array or object.
Array is not very useful if you want to display an error for each field separately. It is not for us.
Object contains only the last error:
req;req; var errors = req;
Here the errors
will contain message for format validation instead notEmpty()
check. So you have to do the checking in reverse order. This is the first problem.
Adding errors
req.validationErrors(true)
can return null
or object
with errors and we should check it. Also error for a particular field may already be in the object and we should check it too:
req;req; var errors = req; User;
If we do not check this, our error will appear even when unfilled or incorrect e-mail address.
It becomes routine, when we do more of checks like this.
Tests
npm test
npm run-script test-cov
License
MIT