diff --git a/lib/validation.js b/lib/validation.js index 48b38d8..1522a00 100644 --- a/lib/validation.js +++ b/lib/validation.js @@ -49,11 +49,47 @@ module.exports = function (req, res, next) { // validate JSON validation = revalidator.validate(req.body, resource); - err = validation.valid ? err : validation; + err = validation.valid ? err : transform(validation); + next(err); } else { // continue next(err); } -} \ No newline at end of file +} + +/** + * Transform revalidator errors into human redable errors. + */ + +function transform(validation) { + var err = {} + , errors = validation.errors + , e + , prop + ; + + for(var i = 0, len = errors.length; i < len; i++) { + e = errors[i]; + prop = e.property; + + switch(e.attribute) { + case 'type': + err[prop] = 'must be a ' + e.expected; + break; + case 'required': + err[prop] = 'is required'; + break; + default: + err[prop] = 'is not valid' + break; + } + } + + // rename and add human readable errors + validation.validation = validation.errors; + validation.errors = err; + + return validation; +} diff --git a/test/validation.test.js b/test/validation.test.js index bcbf947..adc30e6 100644 --- a/test/validation.test.js +++ b/test/validation.test.js @@ -12,10 +12,11 @@ describe('Resource Actions', function(){ describe('POST /todos', function(){ it('should return an error when provided invalid data', function(done) { - todos.post({title: 123}, function (err, todo, req, res) { + todos.post({foo: 123, completed: 'flarg'}, function (err, todo, req, res) { expect(err).to.exist; expect(err.valid).to.equal(false); - expect(err.errors).to.have.length(1); + expect(err.validation).to.have.length(2); + expect(err.errors).to.be.a('object'); expect(todo).to.not.exist; done(); })