Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

241
Views
Express validator check if input is one of the options available

Currently I have html Code like this:

<!DOCTYPE html>
<html>
<body>

<p>Select an element</p>

<form action="/action">
  <label for="fruit">Choose a fruit:</label>
  <select name="fruit" id="fruit">
    <option value="Banana">Banana</option>
    <option value="Apple">Apple</option>
    <option value="Orange">Orange</option>
  </select>
  <br><br>
  <input type="submit" value="Submit">
</form>


</body>
</html>

And on the server side I want so check with the express validator if the fruit in the post request is either a banana, an apple or an orange. This is the code I have so far:

const{body} = require('express-validator');

const VALIDATORS =  {
    Fruit: [
        body('fruit')
            .exists()
            .withMessage('Fruit is Requiered')
            .isString()
            .withMessage('Fruit must be a String')
    ]
}

module.exports = VALIDATORS;

How do I check if the string sent by the POST request is one of the required fruit?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Since express-validator is based on validator.js , a method you could use for this case should already be available. No need for a custom validation method.

From the validator.js docs , check if the string is in a array of allowed values:

isIn(str, values)

You can use this in the Validation Chain API, in your case like :

body('fruit')
 .exists()
 .withMessage('Fruit is Requiered')
 .isString()
 .withMessage('Fruit must be a String')
 .isIn(['Banana', 'Apple', 'Orange'])
 .withMessage('Fruit does contain invalid value')

This method is also included in the express-validator docs, here https://express-validator.github.io/docs/validation-chain-api.html#not (it is used in the example for the not method)

over 4 years ago · Santiago Trujillo Report

0

You can do it via .custom function;

For example:

body('fruit').custom((value, {req}) => {
  const fruits = ['Orange', 'Banana', 'Apple'];
  if (!fruits.includes(value)) {
    throw new Error('Unknown fruit type.');
  }

  return true;
})
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!