Home > Enterprise >  ExpressJS validation
ExpressJS validation

Time:10-04

the following if condition does not work:

I still have the possibility to register with numbers instead of strings.

enter image description here

CodePudding user response:

It's likely that req.body.firstName and req.body.lastName are coming in as a stringed numbers e.g.:

{
   "firstName": "4",
   "lastName": "187"
}

so typeof will still consider them as strings. You can use a regex if you really hate numbers.

const { firstName, lastName } = req.body;
if (firstName.match(/^\d*(\.\d )?$/) || lastName.match(/^\d*(\.\d )?$/)) {
  return res.status(422).json({
    message: 'Name provides letters, not numbers!',
  })
}

or I would suggest you use a validation library like Joi or validate.js to avoid building an API with possible security holes.

  • Related