简体   繁体   中英

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) => { ... }
];

尝试为每个复选框使用与应用isIn([])相同的名称,以按照以下方式进行验证: https : //express-validator.github.io/docs/check-api.html

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM