Sunday, 12 March 2017

check req.body.property.childProperty inside req.checkBody()

In nodejs we commonly do something like:

req.checkBody('name', 'Group name is required.').notEmpty();

Similarly, I have done something like this:

req.checkBody('parent.name', 'Parent Name and group name should be different.').checkEquality(name);

Here check equality is a function defined in middleware like this:

app.use(expressValidator({
    customValidators: {
        checkEquality: function(firstInput, secondInput) {
            return firstInput.toLowerCase() != secondInput.toLowerCase();
        }
    }
}));

As you can see in the above code that checkEquality is just a function which returns if firstInput is equal to secondInput.

If req.body.parent is an object then

Every thing goes right and all validations pass or fail successfully as needed.

If req.body.parent is string then

I get an error saying firstInput.toLowerCase() is not a function.

The error is somewhat confusing but I know what the error mean: The error means that firstInput is undefined and undefined does not have a function toLowerCase.

Also, I understand that if req.body.parent is a string then parent.name will always be undefined.

So, I tried:

req.checkBody(('parent.name' == undefined ? 'parent' : 'parent.name'), 'Parent Name and group name should be different.').checkEquality(name);

But still no luck. Getting same errors.

I mean still using this code, if req.body.parent is an object I get everything going smoothly. But if req.body.parent is a string then everything is bad and gives errors as mentioned above.



via Vishal

No comments:

Post a Comment