Search code examples
javascriptnode.jsexpressvalidationserver-side

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?


Solution

  • 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)