OscarDev
OscarDev

Reputation: 977

Pass two values ​to custom validation with express-validation

I need to receive two values ​​to search for a subdocument using the main ID of the document and then another ID of the subdocument.

I receive these ID's by the parameters and using express-validator I am using a custom function to verify that they exist in this way:

router.put('/:id/item/:idItem',   
    [        
        check('id','idItem').custom( idItemExists )
    ],
    validation,
    updateItem 
);

And in my function called idItemExists() I try to receive both values ​​but the second value, when passed to the console, returns everything that comes from the request:

let idItemExists = async ( id, idItem ) => { 
    console.log(idItem);
}

Response Capture

In this case I need to be able to receive both values ​​correctly in order to validate if both IDs are correct.

Thanks a lot.

Upvotes: 1

Views: 1349

Answers (1)

BaDr Amer
BaDr Amer

Reputation: 910

this will not work since .custom takes a function that receives the value of the field being validated, as well as the express request, the location and the field path as mentioned in their docs.

validator(value, { req, location, path })

in your case you're trying to log the object that contains the req, location and the path.

in order to get both values inside a custom validator you could do the following:

 param() // when we omit fields, then we're getting all fields inside req.params
    .custom(params => { // here we ignore the second parameter { req, location, path }
        console.log(params) // { id: '10', idItem: '20' }
    })

Upvotes: 2

Related Questions