Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match string with values from array in express-validation

I am using express-validator to validate input to my API, but I have some problems understanding the matches function. I basically need to be able to figure out if a string matches any of the values in an array of accepted values, like shown below, but it doesn't seem to work. Any suggestions?

var schema = {
  "role": {
    in: 'body',
    matches: {
      options: ["administrator", "editor", "contributor", "user"],
      errorMessage: "Invalid role"
    }
  }
}

req.check(schema)
like image 727
2famous.TV Avatar asked Dec 22 '16 18:12

2famous.TV


2 Answers

The matches.options constructs a regex. You can pass in your regex as the first element of the array. Try this:

var schema = {
  "role": {
    in: 'body',
    matches: {
      options: [/\b(?:administrator|editor|contributor|user)\b/],
      errorMessage: "Invalid role"
    }
  }
}
like image 110
mkhanoyan Avatar answered Oct 09 '22 02:10

mkhanoyan


As an alternative you can use this schema:

 var schema = {
  "role": {
    in: 'body',
    isIn: {
      options: [["administrator", "editor", "contributor", "user"]],
      errorMessage: "Invalid role"
    }
  }
}

More on this issue.

like image 44
Ahmad Jahanbin Avatar answered Oct 09 '22 00:10

Ahmad Jahanbin