-
-
Notifications
You must be signed in to change notification settings - Fork 616
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Validate array of objects? #67
Comments
I have the same problem with items of array |
Related issue here: #125. There is a solution offered in that issue. Please continue the conversation there. |
@rustybailey @gustavohenke @IOAyman I don't think this is same issue as #125. I think the OP was asking what if the Example JSON -
How do I begin to validate this. What argument do I provide to |
What about this? |
@jyotman did u find a workaround for this ? is there a way to validate the objects in the array iteself? pretend the post payload looks something like below. how to validate name is string and age is int in the array.
|
@foodaka I did something like this - for(let i = 0; i < req.body.length; i++) {
req.checkBody([i, 'name']).notEmpty();
req.checkBody([i, 'age']).isInt();
} |
I was able to do it with wildcards like this: /* Raw alerts fired from Prometheus Server */
app.post('/api/v1/alerts', [
body().isArray(),
body('*.labels', 'labels field must be a JSON object').exists().isJSON(),
body('*.annotations', 'annotations field must a JSON object').exists().isJSON(),
body('*.startsAt', 'startsAt field must be a string').exists().isString(),
body('*.endsAt', 'endsAt field must be a string').exists().isString(),
body('*.generatorURL', 'generatorURL field must be a URL').exists().isURL({ require_tld: false })
], (req, res) => {
// Finds the validation errors in this request and wraps them in an object with handy functions
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
alerts = req.body;
return res.status(200).json(alerts);
}); where my [{
"labels": {
"alertname": "IOWarning",
"device": "sda",
"instance": "localhost:9100",
"job": "node",
"severity": "warning"
},
"annotations": {
"description": "I/O Usage Read/Write: This is dangerous and rectified immediately",
"summary": "I/O Usage Read/Write Alert"
},
"startsAt": "2018-08-06T17:16:54.26404133Z",
"endsAt": "0001-01-01T00:00:00Z",
"generatorURL": "http://prometheus-server:9090/graph?g0.expr=irate%28node_disk_written_bytes_total%5B1m%5D%29+%3E+0&g0.tab=1"
}] |
I used
Validate array items: |
For me the custom validation of express-validator was the simplest.
|
So how can I validate array of instance based on schema? checkSchema(schema, myArray); Now I have not such possibility, cause checkSchema uses req.body, and when body is |
Hello @ddemydenko, |
I have a post method, that according to restfull api can accepts one instance or array of the same instances. So I looking for a possibility using this approach Schema Validation to bulk create :
I already have a schema, that works fine for one instance but I want apply it for many instances. How I can iterate array? |
Regardless of the checkSchema, I've put your request in my 'check' example.
|
Here is my server: const express = require('express');
const expressValidator = require('express-validator');
const { checkSchema } = require('express-validator/check');
const app = express();
const port = 3000;
const schema = require('./schema.json');
app.use(express.json());
app.use(expressValidator());
app.post('/users',checkSchema(schema), (req, res) => {
const err = req.validationErrors();
console.log(err);
res.send(err)
});
app.listen(port); Here is my schema.json {
"guid": {
"isEmpty": false
},
"url": {
"isEmpty": false,
"isURL": true
},
"amount": {
"isEmpty": false,
"isFloat": true
}
} And here is my single object request, validates as expected
Since I already have a defined schema, therefor to avoid code duplication I want to use this schema to validate multi objects creation, aka bulkCreate
But this case works wrong. Validation failed, Because checkSchema consider body like a single object. |
Ok, folks, it is very unobvious, and this trick undocumented. I had to add asterisk
|
@ddemydenko it's documented under wildcards. I'm locking the conversation since this is a 5 years old issue which has had a solution for a while now. |
When I submit a single object as my payload I can validate keys very easily with:
But I would like to submit an array of objects and loop through them with something like:
I've also tried using
req.assert
withelement.year
and evenelement.year.toString()
with no luck.What am I doing wrong? Or is this type of functionality even possible?
The text was updated successfully, but these errors were encountered: