Lanti
Lanti

Reputation: 2329

Unexpected behaviour in Express form validation router

I have this code in a router.post which will validate my input form with the help of 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');
};

Expected output:

Experienced behaviour:

I also experiencing serious lag after many re-request in a row with the following console error: main-vanilla.min.js:1 POST http://127.0.0.1:3000/hu/form net::ERR_EMPTY_RESPONSE

Upvotes: 0

Views: 28

Answers (1)

go-oleg
go-oleg

Reputation: 19480

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.');
}

has a couple things wrong with it:

  1. You are missing the [0] after the .match() which you do have in the firstname.match(). match() returns an Array so you need to select the first element.

  2. Right now the logic says if one of these does not match, then throw an error. What you actually want is, if none of these match, throw an error. You should use && instead of || to achieve that.

Upvotes: 1

Related Questions