Search code examples
node.jsexpress-validator

How to validate checkbox values using express-validator?


In my web front end form, I am using checkbox to select list of companies for each checkbox entry, I have given company name as 'value' attribute. In nodejs, I use express-validator to check the form. I am not clear how to validate and sanitize user input for these checkbox items.

I see all the example of express validator uses form parameter name to check a specific parameter (eg) check('userName') as middleware. But for checkboxes particular parameter will be present only when the user select that parameter. If I have 10 options and user select only 4 of them, then req.body will have only these parameters . And also I want all them pass through same validation check and sanitization. Please suggest how to do it.

I am using NodeJS version: 10.8 Express Validator: 5.3.0 My checkbox values are company_a1,company_a2,...company_a10. I tried to write custom Validator and check for each of the body parameter for alphanumeric value, but check is not raising error even if the value contain alphanumeric strings

async function validateReportParams(body, { req, loc, rpath }) {

 for (const par of Object.keys(req.body)) {
    try {
      check(req.body[par].isAlphanumberic());
    } catch (err) {
        return Promise.reject(err);
    }
  }
}
exports.genReport = [
  validateReq,
  param().custom(validateReportParams),
  async (req, res, next) => { ... }
];


Solution

  • Try using the same name for each checkbox than apply isIn([]) to validate as per: https://express-validator.github.io/docs/check-api.html

    check(req.body.checkbox.isIn(['company_a1','company_a2',...,'company_a10']));