如何让express-validator的isAlphanumeric函数忽略单引号?
解决express-validator中isAlphanumeric允许单引号验证失败的问题
问题核心在于**.escape()方法的执行顺序错误**:
.escape()会将输入中的单引号(')转义为HTML实体'- 转义后的字符不在
isAlphanumeric的ignore列表(" -'")中,导致验证失败
修正前代码
body("title") .trim() .isLength({ min: 1 }) .escape() .withMessage("Le champ titre est obligatoire.") .isAlphanumeric("fr-FR", { ignore: " -'" }) .withMessage("Le champ titre contient des caractères non autorisés.")
修正后代码
body("title") .trim() .isLength({ min: 1 }) .withMessage("Le champ titre est obligatoire.") .isAlphanumeric("fr-FR", { ignore: " -'" }) .withMessage("Le champ titre contient des caractères non autorisés.") .escape()
将.escape()移到isAlphanumeric验证之后,先对原始输入的单引号进行合法性校验,再执行转义处理,即可解决单引号触发验证错误的问题。
内容的提问来源于stack exchange,提问作者siana-blue
相关产品推荐
相关产品推荐

