Express validator check if input is one of the options available
Asked Answered
S

3

7

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?

Schwaben answered 21/1, 2021 at 9:21 Comment(1)
you can use .matches() method like: .matches('Apple')Ouzel
D
26

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)

Drawing answered 21/1, 2021 at 9:47 Comment(1)
Thank you! It helped me out a lot!Schwaben
S
2

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;
})
Sediment answered 21/1, 2021 at 9:33 Comment(0)
R
0

Make sure when using a validation schema you pass the array inside another array in the options field for isIn

checkSchema({
  weekend: {
    // WRONG - Translates to `isIn('saturday', 'sunday')`
    isIn: { options: ['saturday', 'sunday'] },
    // RIGHT - Translates to `isIn(['saturday', 'sunday'])`
    isIn: { options: [['saturday', 'sunday']] },
  },
});
Rexfourd answered 13/1 at 20:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.