我在 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
。
经验丰富的行为:
-
在验证
captcha
总是向console.log
抛出错误。firstname
按预期工作。
firstname
后,在连续多次重新请求后,我也遇到了严重的延迟,并出现以下控制台错误: main-vanilla.min.js:1 POST http://127.0.0.1:3000/hu/form net: :ERR_EMPTY_RESPONSE
最佳答案
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.');
}
有几个问题:
您在
firstname.match()
中的.match()
后面缺少[0]
>。match()
返回一个数组,因此您需要选择第一个元素。现在的逻辑是,如果其中一个不匹配,则抛出错误。您真正想要的是,如果这些都不匹配,则抛出错误。您应该使用
&&
而不是||
来实现这一点。
关于javascript - Express 表单验证路由器中的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37333643/