Adam W
Adam W

Reputation: 285

express-validator Integer or null

I need to do simple validation and allow only Integer values or null. I'm using express-validator 7.2.0 and I'm having a hard time implementing it...

here is my validation middleware:

check('contactID')
        .optional({nullable: true})
        .not()
        .isInt(),

I cannot use .optional({nullable: true}) because that is allowing to skip that field entirely and if skipped then sql query is sending "undefined" - (sql error willl be returned).

I also cannot use .exists() because exists can be used only if no other checks are present.

I cannot use isInt() because it won't allow null.

if I use

check('contactID')
        .isNumeric()
        .withMessage('only numeric allowed'),

it won't let {"contactId": null}

this is almost working - it only accepts Integer, it will take null however if I remove it entirely from payload validation will be positive and SQL error will be returned: Invalid column name 'undefined'

check('contactID')
        .isInt()
        .optional({nullable: true}),

Seems like I'm out of options to do simple (what it seems) validation.

Upvotes: 0

Views: 56

Answers (0)

Related Questions