I am using Express-Validator to validate some query parameters to a RESTful API written in node.js. I would like to “bail()” after running the mandatory checks so that there will be a message for each of the missing params, but not for subsequent checks on their values. Here are some sample errors demonstrating the issue. You can see that the missing fields are reported, but then there is also an error about the ticker symbol format (which I don’t want to mix with messages about missing params):
{
"errors": [
{
"type": "field",
"msg": "The target rate of return ("rate" parameter) is mandatory.",
"path": "rate",
"location": "query"
},
{
"type": "field",
"msg": "The number of years to achieve the target rate of return ("years" parameter) is mandatory.",
"path": "years",
"location": "query"
},
// I DON'T WANT TO GET INTO FORMAT VALIDATION IF THERE ARE ANY MISSING FIELDS.
{
"type": "field",
"value": "33",
"msg": "The stock ticker symbol ("symbol" parameter) may only contain letters, i.e., "c", "KO", "Mmm", or "TSLA".",
"path": "symbol",
"location": "query"
}
]
}
I don’t want to validate any param values if there are any missing params. In other words, I want to validate mandatory fields as a group, and then only proceed IF there are no missing params.
I can’t use bail() because that stops validation after one specific param. I think I need to create a ValidationChain (or maybe use the custom() function?), but I’m not sure how to do that.
Here is my (simplified) validation code:
app.get('/', [
// either the symbol or the price and rate params are required
oneOf([
query('symbol').exists()
[
query('price').exists(),
query('rate').exists()
]
],
query('targetRate').exists(),
query('years').exists(),
// don't run these checks if any of the above params are missing
query('market').isAlpha('en-US'),
query('numOfShares').isDecimal()
Maybe all of the checks for mandatory fields needs to be moved to it’s own function. I’m just not sure how to do that. Any ideas?