lll
lll

Reputation: 65

How do I validate number range in NodeJS

When I console.log(req.body.sectionAData), I got this result:

{
  sectionAData: { AQ1: '5', AQ2: '4', AQ3: '5' }
}

So I continue with this:

const { AQ1, AQ2, AQ3} = req.body.sectionAData   
console.log( AQ1, AQ2, AQ3)

and the result is:

5 4 5

What I'm trying to achieve is to validate all the AQ1, AQ2 and AQ3 are within the range of 1 to 5

If either one is not in range, then json.send a message.

How should I go about it? Thanks

Upvotes: 1

Views: 234

Answers (2)

Youssouf Oumar
Youssouf Oumar

Reputation: 46023

You could do it like below, with a checkRange helper function:

const checkRange=(v)=> v>=1 && v <=5;

if(checkRange(AQ1) && checkRange(AQ2) && checkRange(AQ3)){
  // send ok response
}else{
  // send bad response
}

Upvotes: 0

Vladimir Trotsenko
Vladimir Trotsenko

Reputation: 246

You can do like this:

const check = [AQ1, AQ2, AQ3].every(e => e >= 1 && e <= 5)
if (!check) { 
  // do stuff 
}

Upvotes: 1

Related Questions