question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Validating Array objects for required fields, .exists() - doesn't seem to work

See original GitHub issue

I am able to validate requests with latest version 5, works great, but facing one issue with arrays. Is there a way to force that a field must be present in array object? the exists() doesn’t seem to work for arrays.

...
  return [
        check('items').exists(), //WORKS GREAT
        check('items.*._id').exists().isAlphanumeric(), //EXISTS() IS IGNORED  BUT WILL VALIDATE IF FIELD IS PRESENT :((
        check('items.*.item_type').exists().isIn(Item.ITEM_TYPES), //SAME HERE, EXISTS() IS IGNORED  BUT WILL VALIDATE IF FIELD IS PRESENT :((
check('items.*.update_status').exists().isInt().isIn(Constants.UPDATE_STATUS_VALUES).withMessage("must be one of:"+JSON.stringify(Constants.UPDATE_STATUS)),
        sanitize('items.*.long_desc').toString(),
    ];

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:3
  • Comments:14 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
jonathonluicommented, Mar 5, 2018

@davida5 see https://github.com/ctavan/express-validator#check-api

Simply change check() to body(). Example:

...

exampleValidation = [
  body('items').exists().withMessage('missing'),
  body('items.*._id').isAlphanumeric(),
  body('items.*.item_type').exists().isIn([1, 2, 3]),
];

app.post('/example', exampleValidation , (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.mapped() });
  }
 ...
})

...

And it’ll check each item. For example a request with 2 invalid item and 1 valid item results in 2 errors:

POST /example HTTP/1.1
Accept: application/json, */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 83
Content-Type: application/json
Host: localhost:3000
User-Agent: HTTPie/0.9.9

{
    "items": [
        {
            "_id": "myid"
        },
        {
            "item_type": 1
        },
        {
            "_id": "gooditem",
            "item_type": 2
        }
    ]
}

HTTP/1.1 400 Bad Request
Connection: keep-alive
Content-Length: 184
Content-Type: application/json; charset=utf-8
Date: Mon, 05 Mar 2018 18:20:37 GMT
ETag: W/"b8-Uplw/sru0nh8L0Px5DDKkmqTICU"
X-Powered-By: Express

{
    "errors": {
        "items[0].item_type": {
            "location": "body",
            "msg": "Invalid value",
            "param": "items[0].item_type"
        },
        "items[1]._id": {
            "location": "body",
            "msg": "Invalid value",
            "param": "items[1]._id"
        }
    }
}
1reaction
gustavohenkecommented, Mar 5, 2018

Hey @davida5, the right name is body. See docs for more reference.

Also, while skimming through the issue, the feeling I have is that * is only working for the first results it encounters. Is it correct?

If so we’ll need some serious bug fixing 🙂

Read more comments on GitHub >

github_iconTop Results From Across the Web

Class-validator - validate array of objects - Stack Overflow
Add @Type(() => AuthParam) to your array and it should be working. Type decorator is required for nested objects(arrays). Your code becomes
Read more >
Validation - Laravel - The PHP Framework For Web Artisans
This object exposes only , except , and all methods to retrieve a subset of the validated data or the entire array of...
Read more >
How to validate array fields? - Laracasts
Not sure how to get this to work though, I've tried: Copy Code roles' => 'array|each|exists:roles,id'. But that doesn't work.
Read more >
Working with Angular 4 Forms: Nesting and Input Validation
In this article, you will learn how you can work with forms and perform form validation with ease in your Angular application. In...
Read more >
Why does Mongoose remove the key when specified in the ...
Here's what happens: When I specify the schema for an array of objects (may be doing this wrong), that particular key and all...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found