Added validation for embedded items (optional)
This commit is contained in:
parent
59a957b538
commit
1487a592c1
|
@ -1422,6 +1422,29 @@ RelationDefinition.embedsMany = function hasMany(modelFrom, modelTo, params) {
|
|||
}, { code: 'uniqueness' })
|
||||
}
|
||||
|
||||
// validate all embedded items
|
||||
if (definition.options.validate) {
|
||||
modelFrom.validate(relationName, function(err) {
|
||||
var embeddedList = this[relationName] || [];
|
||||
var hasErrors = false;
|
||||
embeddedList.forEach(function(item) {
|
||||
if (item instanceof modelTo) {
|
||||
if (!item.isValid()) {
|
||||
hasErrors = true;
|
||||
var first = Object.keys(item.errors)[0];
|
||||
var msg = 'contains invalid item: `' + item[idName] + '`';
|
||||
msg += ' (' + first + ' ' + item.errors[first] + ')';
|
||||
this.errors.add(relationName, msg, 'invalid');
|
||||
}
|
||||
} else {
|
||||
hasErrors = true;
|
||||
this.errors.add(relationName, 'Contains invalid item', 'invalid');
|
||||
}
|
||||
}.bind(this));
|
||||
if (hasErrors) err(false);
|
||||
});
|
||||
}
|
||||
|
||||
var scopeMethods = {
|
||||
findById: scopeMethod(definition, 'findById'),
|
||||
destroy: scopeMethod(definition, 'destroyById'),
|
||||
|
|
|
@ -1380,7 +1380,7 @@ describe('relations', function () {
|
|||
});
|
||||
|
||||
it('can be declared', function (done) {
|
||||
Person.embedsMany(Address, { options: { autoId: false } });
|
||||
Person.embedsMany(Address, { options: { autoId: false, validate: true } });
|
||||
db.automigrate(done);
|
||||
});
|
||||
|
||||
|
@ -1451,6 +1451,19 @@ describe('relations', function () {
|
|||
});
|
||||
});
|
||||
|
||||
it('should validate all embedded items', function(done) {
|
||||
var addresses = [];
|
||||
addresses.push({ id: 'home', street: 'Home Street' });
|
||||
addresses.push({ id: 'work', street: '' });
|
||||
Person.create({ name: 'Wilma', addresses: addresses }, function(err, p) {
|
||||
err.name.should.equal('ValidationError');
|
||||
var expected = 'The `Person` instance is not valid. ';
|
||||
expected += 'Details: `addresses` contains invalid item: `work` (street can\'t be blank).';
|
||||
err.message.should.equal(expected);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
});
|
||||
|
|
Loading…
Reference in New Issue