I have some req.body content I want to validate. I used this line to get a sense of what the data looks like when it is passed into the validation function:
body('ids').custom(value => {return console.log(value)} )
And that produces this:
[
'D93A4C60-C09A-47FF-B87F-28732B6FEB79',
'D93A4C60-C09A-47FF-B87F-28732B6FEB79'
]
It should be noted that that array is of an arbitrary length greater than or equal to 1.
I want to validate this with the following body check:
body('ids', 'error message').matches(REGEX)
Below is the regex I have made.
(\['[0-9a-zA-Z]{8}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{12}')(,'[0-9a-zA-Z]{8}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{12}')+\]
Whenever I test that regex in this tool (https://regexr.com/) it works but it does not correctly validate in my express app and I think it's because of the line breaks but I'm not sure how to verify or validate that.
Is there a better way to handle what I am trying to do here?
Why don't you use a custom validator and then iterate through the value list. Then you can manually test each element in the list with your regex. I think the express-validator matches() function is better suited for single params. This is my take on how to handle this issue:
body('ids').custom(value => {
value.forEach(element => {
if (!value.match('[0-9a-zA-Z]{8}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{12}')) {
throw new Error('Invalid Input!')
};
});
})