Skip to content

Commit

Permalink
Validator#validate: add "required" option
Browse files Browse the repository at this point in the history
  • Loading branch information
awwright committed Oct 20, 2020
1 parent abfea4b commit 5a8649d
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ ValidationError.prototype.toString = function toString() {
var ValidatorResult = exports.ValidatorResult = function ValidatorResult(instance, schema, options, ctx) {
this.instance = instance;
this.schema = schema;
this.options = options;
this.path = ctx.path;
this.propertyPath = ctx.propertyPath;
this.errors = [];
Expand Down
5 changes: 5 additions & 0 deletions lib/validator.js
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,11 @@ Validator.prototype.validate = function validate (instance, schema, options, ctx
ctx.schemas[n] = sch;
}
}
if(options.required && instance===undefined){
var result = new ValidatorResult(instance, schema, options, ctx);
result.addError('is required, but is undefined');
return result;
}
var result = this.validateSchema(instance, schema, options, ctx);
if (!result) {
throw new Error('Result undefined');
Expand Down
20 changes: 20 additions & 0 deletions test/Validator.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -154,5 +154,25 @@ describe('Validator', function () {
it('options.base must be a string', function () {
validator.validate(null, true, null);
});
it('options.required with defined instance', function () {
var res = validator.validate(undefined, true, {required: true});
assert(!res.valid);
console.error(res.errors);
assert(res.errors[0].message.indexOf('required') >= 0);
});
it('options.required with undefined instance', function () {
var res = validator.validate(undefined, true, {required: true});
assert(!res.valid);
assert(res.errors[0].message.indexOf('required') >= 0);
});
it('options.required is false', function () {
var res = validator.validate(undefined, true, {required: false});
assert(res.valid);
});
it('options.required defaults false', function () {
// TODO DEPRECATED: this behavior changes to true in next major version
var res = validator.validate(undefined, true, {});
assert(res.valid);
});
});
});

0 comments on commit 5a8649d

Please sign in to comment.