Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Express Validator not allowing null values in optional fields?

I am using express-validator to validate a form, but many of the fields are optional. I have configured the validator on my route like such:

const ExpValidate = require('express-validator');
router.post('/api/posthandler', 
[ ExpValidate.body("TopicID").optional({nullable: true, checkFalsy: true}).trim().isInt(), ]
async function(req, res) {
    const errors = ExpValidate.validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(422).json({ errors: errors.array() });
    }
    else {
    // Handle form here

}

When a form is submitted with TopicID: null, I am getting an error saying:

{
    "errors": [
        {
            "value": "null",
            "msg": "Invalid value",
            "param": "TopicID",
            "location": "body"
        }
    ]
}

I get the same error even if I remove the options {nullable: true, checkFalsy: true} from the optional() method.

I do not get any error if I just do ExpValidate.body("TopicID").optional() but that defeats the point of the validator which is to check isInt() if a value is provided.

If I do not submit TopicID at all, then I also get no errors.

Is there something wrong with my configuration?

UPDATE: Although this question was a while ago, what was happening is that Form data sends EVERYTHING as a string. So null cannot be passed as typeof null, it will be passed as a string "null". Therefore nullable check does not work with Form data (it will work with JSON data however).

like image 285
volume one Avatar asked Jun 07 '26 14:06

volume one


1 Answers

On a hunch I tried reversing the method calls. This validator worked for me:

body("date_field").isDate().optional({ nullable: true }),

using this input:

{
  "date_field": null
}

Looks like the optional() call needs to be last!

like image 53
phunque Avatar answered Jun 10 '26 05:06

phunque