You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 14:22:07