不要怂,就是干,撸起袖子干!

Commit 8be24f37 by Brian Romanko

Adding a method to find validation errors by path

1 parent 9c7500d7
Showing with 50 additions and 2 deletions
......@@ -30,12 +30,45 @@ error.BaseError.prototype = Object.create(Error.prototype, {
*
* @constructor
*/
error.ValidationError = function() {
error.ValidationError = function(message, errors) {
error.BaseError.apply(this, arguments);
this.name = 'SequelizeValidationError';
this.errors = errors || [];
return this;
};
error.ValidationError.prototype = Object.create(error.BaseError.prototype, {
constructor: { value: error.ValidationError }
});
/**
* Finds all validation error items for the path specified.
*
* @param {string} path The path to be checked for error items
* @returns {Array} Validation error items for the specified path
*/
error.ValidationError.prototype.errorsForPath = function(path) {
return this.errors.reduce(function(reduced, error) {
if (error.path === path) {
reduced.push(error);
}
return reduced;
}, []);
};
/**
* Validation Error Item
* Instances of this class are included in the ValidationError errors property.
*
* @param {string} message An error message
* @param {string} type The type of the validation error
* @param {string} path The field that triggered the validation error
* @param {string} value The value that generated the error
* @constructor
*/
error.ValidationErrorItem = function(message, type, path, value) {
this.message = message || '';
this.type = type || null;
this.path = path || null;
this.value = value || null;
};
\ No newline at end of file
......@@ -30,6 +30,20 @@ describe(Support.getTestDialectTeaser("Sequelize Errors"), function () {
expect(validationError).to.have.property('name', 'SequelizeValidationError');
expect(instError).to.be.instanceOf(Sequelize.Error);
expect(instValidationError).to.be.instanceOf(Sequelize.ValidationError);
})
});
it('SequelizeValidationError should find errors by path', function() {
var errorItems = [
new Sequelize.ValidationErrorItem('invalid', 'type', 'first_name', null),
new Sequelize.ValidationErrorItem('invalid', 'type', 'last_name', null)
];
var validationError = new Sequelize.ValidationError('Validation error', errorItems);
expect(validationError).to.have.property('errorsForPath');
expect(validationError.errorsForPath).to.be.a('function');
var matches = validationError.errorsForPath('first_name');
expect(matches).to.be.instanceOf(Array);
expect(matches).to.have.lengthOf(1);
expect(matches[0]).to.have.property('message', 'invalid')
});
})
});
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!