Brijesh Bhakta Brijesh Bhakta - 1 year ago 95
Node.js Question

Custom response message which validates all required parameters in Node js

I'm new to NodeJS and Express and I want to validate APIs parameters.
For now I validate parameters by:

return res.send({"message": "Please provide parametername"});

return res.send({"message": "parametername can not be blank"});

But I want the response to be like:

"username": [
"This field is required."
"password": [
"This field can not be blank."

This is the response I want if the parameters are invalid or not provided.

Answer Source

You may find express-validator to be what you need here. In particular this section:

req.assert('email', 'required').notEmpty();
req.assert('email', 'valid email required').isEmail();
req.assert('password', '6 to 20 characters required').len(6, 20);

var errors = req.validationErrors(); // Or req.asyncValidationErrors();
var mappedErrors = req.validationErrors(true); // Or req.asyncValidationErrors(true);

mappedErrors will look like this:

  email: {
    param: "email",
    msg: "valid email required",
    value: "<received input>"
  password: {
    param: "password",
    msg: "6 to 20 characters required",
    value: "<received input>"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download