Express validator check if input is one of the options available

Viewed 7191

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?

2 Answers

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)

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;
})
Related