【问题标题】:Unexpected behaviour in Express form validation routerExpress 表单验证路由器中的意外行为
【发布时间】:2016-05-19 20:41:45
【问题描述】:

我在 router.post 中有这段代码,它将在 ajax 的帮助下验证我的输入表单:

if(req.body.firstname === '' || req.body.firstname !== req.body.firstname.match(/\D+/g)[0]) {
  console.log('AJAX ERROR: Firstname is empty and/or have a number.');
}
else if(req.body.captcha !== req.body.captcha.match(/^kettő$/igm) ||
        req.body.captcha !== req.body.captcha.match(/^ketto$/igm) ||
        req.body.captcha !== req.body.captcha.match(/^two$/igm)) {
  console.log('AJAX ERROR: captcha is empty and/or the entered value is invalid.');
}
else {
  console.log('AJAX ERROR');
};

预期输出:

  • 如果firstname 为空,则在console.log 中抛出错误
  • 如果firstname 有数字,则在console.log 中抛出错误
  • 如果captcha 不等于kettő, ketto, Kettő, Ketto, KETTŐ, KETTO, two, Two, TWO 答案,则在console.log 中抛出错误
  • 如果不满足这些要求,请抛出else

经验丰富的行为:

  • 在验证firstname 之后,captcha 总是向console.log 抛出错误。 firstname 按预期工作。

在连续多次重新请求后,我也遇到了严重的延迟,并出现以下控制台错误:main-vanilla.min.js:1 POST http://127.0.0.1:3000/hu/form net::ERR_EMPTY_RESPONSE

【问题讨论】:

    标签: javascript regex node.js forms express


    【解决方案1】:
    else if(req.body.captcha !== req.body.captcha.match(/^kettő$/igm) ||
            req.body.captcha !== req.body.captcha.match(/^ketto$/igm) ||
            req.body.captcha !== req.body.captcha.match(/^two$/igm)) {
      console.log('AJAX ERROR: captcha is empty and/or the entered value is invalid.');
    }
    

    有几个问题:

    1. 您在.match() 之后缺少[0],而firstname.match() 中确实有。 match() 返回一个数组,所以你需要选择第一个元素。

    2. 现在的逻辑是,如果其中一个不匹配,则抛出错误。您真正想要的是,如果这些都不匹配,则抛出错误。您应该使用&& 而不是|| 来实现这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-17
      • 2013-09-16
      • 1970-01-01
      • 2020-01-23
      • 1970-01-01
      相关资源
      最近更新 更多