Merge pull request #16 from orangemug/feature/improve-in-err-reporting

Improve err reporting for 'in' properties
This commit is contained in:
eleith 2015-05-07 07:56:44 -07:00
commit 39425d6c7b
2 changed files with 31 additions and 4 deletions

View File

@ -23,7 +23,6 @@ Rules.prototype.Error = function(message, rule, value) {
}
if (_.isString(value)) message = message.replace(/%v/, value.toString());
if (_.isString(rule)) message = message.replace(/%r/, rule);
return message.replace(/%p/, this.param).replace(/%v/, "value").replace(/%r/, "rule");
@ -33,7 +32,7 @@ Rules.prototype.apply = function(value) {
if (isValueEmpty(value) && !_.isUndefined(this.rules['default'])) {
if ('function' === typeof(this.rules['default'])) {
value = this.rules['default'].call();
} else {
} else {
value = this.rules['default'];
}
}
@ -117,9 +116,14 @@ Rules.prototype.check = function(value) {
if (typeof(checks[property]) === "function") {
var args = this.rules.properties[property];
if (!checks[property].apply(null, [value, args])) throw this.Error("%p failed %r with %v", property);
if (!checks[property].apply(null, [value, args])) {
if (property === 'in')
throw this.Error("'%p' failed '%r' with '%v' not one of [" + args.join(', ') + "]", property, value)
else
throw this.Error("'%p' failed '%r' with '%v'", property, value);
}
} else if (typeof(this.rules.properties[property]) === "function") {
if (!this.rules.properties[property].apply(null, [value])) throw this.Error("%p failed on %r with %v", property);
if (!this.rules.properties[property].apply(null, [value])) throw this.Error("'%p' failed on '%r' with '%v'", property, value);
}
}

View File

@ -39,4 +39,27 @@ describe("schema errors", function()
expect(!input3.valid).to.be.ok;
expect(input3.errors.sound).to.equal('sound is missing');
});
it("'in' property errors", function()
{
var schema = schemajs.create(
{
sound: {
type:"string",
properties:{
in: ["meow", "purr"]
}
}
});
var input1 = schema.validate({sound: 'meow'});
var input2 = schema.validate({sound: 'purr'});
var input3 = schema.validate({sound: 'bark'});
expect(input1.data.sound).to.equal('meow');
expect(input1.valid).to.be.ok;
expect(input2.data.sound).to.equal('purr');
expect(input2.valid).to.be.ok;
expect(input3.errors.sound).to.equal("'sound' failed 'in' with 'bark' not one of [meow, purr]");
});
});