volume one
volume one

Reputation: 7563

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).

Upvotes: 7

Views: 15708

Answers (4)

Priyank
Priyank

Reputation: 371

I tried researching but couldn't find a good, simplistic solution, so I tried the following approach to allow null values in case of optional validation:

 body('date_field')
.optional()
.if(value=>value!==null)
.isInt().withMessage('Please enter a valid number!')

Upvotes: 0

Jaspal Singh
Jaspal Singh

Reputation: 51

I have tried this, validator works for me

check
    .body('DCFMethodWeight')
    .isInt()
    .optional({ nullable: true, checkFalsy: true })

I think issue has resolved in latest updates, using the 6.3.1 version.

Upvotes: 5

phunque
phunque

Reputation: 371

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!

Upvotes: 15

volume one
volume one

Reputation: 7563

After much testing and contrary to the docs, it turns out that you cannot pass TopicID: null but you can pass TopicID: "" and it will be treated as optional.

Might be a bug, don't know.

Upvotes: 1

Related Questions