解决express-validator中optional()搭配isNumeric()空值报错问题
解决express-validator可选字段空输入仍触发校验的问题
问题出在.optional()的默认行为上:它仅当字段不存在或值为undefined时才跳过后续校验。但表单提交时,空输入通常会被传递为空字符串"",这时候字段是存在的,所以.isNumeric()这类规则依然会执行,导致“invalid value”错误。
你需要给.optional()传入配置参数,让它在字段值为空字符串、null等“假值”时也跳过校验,具体使用checkFalsy: true选项:
修改后的校验规则示例:
proveedores_controllers.set_proveedor_input_rules = [ body("nombre").isLength({min: 2, max:30}).withMessage("El nombre debe tener entre 2 y 30 caracteres."), body("apellido").isLength({min: 2, max:30}).withMessage("El apellido debe tener entre 2 y 30 caracteres."), // 添加 { checkFalsy: true } 配置 body("cuit").optional({ checkFalsy: true }).isLength({max:18}).withMessage("El cuit debe tener como maximo 18 digitos").isNumeric(), body("direccion").optional({ checkFalsy: true }).isLength({max:30}).withMessage("La direccion debe tener como maximo 30 caracteres."), body("localidad").optional({ checkFalsy: true }).isLength({max:30}).withMessage("La localidad debe tener como maximo 30 caracteres."), body("rubro").optional({ checkFalsy: true }).isLength({max:30}).withMessage("El rubro debe tener como maximo 30 caracteres."), body("telefono").optional({ checkFalsy: true }).isLength({max:18}).withMessage("El telefono debe tener como maximo 18 digitos.").isNumeric(), body("celular").optional({ checkFalsy: true }).isLength({max:18}).withMessage("El celular debe tener como maximo 18 digitos.").isNumeric(), body("email").optional({ checkFalsy: true }).isLength({max:50}).withMessage("El email debe tener como maximo 50 caracteres.").normalizeEmail().isEmail(), body("cbu").optional({ checkFalsy: true }).isLength({max:18}).withMessage("El cbu debe tener como maximo 18 digitos.").isNumeric(), ]
补充说明
checkFalsy: true会把**空字符串""、null、undefined、0、false**都视为“可选”,跳过后续校验,完全匹配表单空输入的场景。- 如果仅需要允许
null或undefined,可改用nullable: true选项,但该配置不会处理空字符串,一般不适用表单场景。
内容的提问来源于stack exchange,提问作者user19729277
相关产品推荐
相关产品推荐

