sylvainpolletvillard / ObjectModel

Strong Dynamically Typed Object Modeling for JavaScript
http://objectmodel.js.org
MIT License
467 stars 28 forks source link

Validation of sub-objects not working as expected #35

Closed thekiwi closed 7 years ago

thekiwi commented 7 years ago

I am finding that ObjectModel ignores the validations of sub-objects in a model.

Take this example:

var Model = require("objectmodel");

function printErrors(errors) {
    console.log("Caught these errors:");
    errors.forEach(function(error){ console.dir(error); });
}

var Address = new Model({
    city: String,
    country: String
}).assert(function(a) { 
    console.log('validation check result: ' + (a.country === "GB"));
    return a.country === "GB";
}, "Country must be GB");

var gbAddress = { city: "London", country: "GB" };
var frAddress = { city: "Paris", country: "FR" };

Address.validate(gbAddress, printErrors); // no errors
Address.validate(frAddress, printErrors); // errors

var Order = new Model({ 
    sku: String,
    address: Address
});

var gbOrder = { sku: "ABC123", address: gbAddress };
var frOrder = { sku: "ABC123", address: frAddress };

Order.validate(gbOrder, printErrors); // no errors
Order.validate(frOrder, printErrors); // no errors, but SHOULD have errors?

Here's the output I'm getting:

running validation check: true
running validation check: false
Caught these errors:
{ message: 'assertion "Country must be GB" returned false for value {\n\tcity: "Paris",\n\tcountry: "FR"\n}' }
running validation check: true
running validation check: false

When you run this, you can see that validation check result: is output 4 times (with the correct result), which correlates with the 4 calls to .validate(...) however only the second call actually causes errors. It seems the Order.validate ignores the validation of the sub-object.

Is this expected behaviour, or a bug? If it is expected, is there a way to enforce an object validation validates all the child model as well?

sylvainpolletvillard commented 7 years ago

Thanks for the report, the bug only concerns assertions checking on submodels. I found how to fix it but won't be able to push a new release before next week.

sylvainpolletvillard commented 7 years ago

Fixed in 2.5.4 :+1: Thanks !

thekiwi commented 7 years ago

@sylvainpolletvillard Thank you!