Skip to content

Commit

Permalink
Allow validators to return strings instead of Error objects
Browse files Browse the repository at this point in the history
  • Loading branch information
Dom Harrington committed Aug 23, 2012
1 parent 9d2c572 commit 84c5928
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,13 +103,13 @@ Validators are functions that have the following signature:
function(name, value, callback) {}
```

The callback must be called with a falsy value (such as undefined or null) if the validation passes, or with an Error object with the appropriate error message if it fails validation.
The callback must be called with a falsy value (such as undefined or null) if the validation passes, or with a string with the appropriate error message if it fails validation.

A full validator example:

```js
var required = function(name, value, callback) {
return callback(value ? undefined : new Error(name + ' is required'));
return callback(value ? undefined : name + ' is required');
};

name: {
Expand Down
6 changes: 4 additions & 2 deletions lib/schemata.js
Original file line number Diff line number Diff line change
Expand Up @@ -283,8 +283,10 @@ module.exports = function(schema) {
validator(propertyName, entityObject[key], validateCallback);
}
}, function(error) {
if (error && error.message) {
errors[key] = error.message;
if (error) {
// Backwards compatibility to allow Error objects to be
// returned from validators as well as just strings
errors[key] = error.message ? error.message : error;
}

seriesCallback(true);
Expand Down
16 changes: 16 additions & 0 deletions test/schemata.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -525,6 +525,22 @@ describe('schemata', function() {
//TODO:
});

it('allows error response to be a string instead of Error object', function(done) {
var schema = createContactSchema()
;

schema.schema.name.validators = {
all: [function(name, value, callback) {
return callback(value ? undefined : name + ' is required');
}]
};

schema.validate(schema.makeDefault({ name: '' }), function(errors) {
errors.should.eql({name:'Full Name is required'});
done();
});
});

});

describe('#propertyName()', function() {
Expand Down

0 comments on commit 84c5928

Please sign in to comment.