Skip to content

Commit 5a8649d

Browse files
committed
Validator#validate: add "required" option
1 parent abfea4b commit 5a8649d

3 files changed

Lines changed: 26 additions & 0 deletions

File tree

lib/helpers.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ ValidationError.prototype.toString = function toString() {
3333
var ValidatorResult = exports.ValidatorResult = function ValidatorResult(instance, schema, options, ctx) {
3434
this.instance = instance;
3535
this.schema = schema;
36+
this.options = options;
3637
this.path = ctx.path;
3738
this.propertyPath = ctx.propertyPath;
3839
this.errors = [];

lib/validator.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,11 @@ Validator.prototype.validate = function validate (instance, schema, options, ctx
124124
ctx.schemas[n] = sch;
125125
}
126126
}
127+
if(options.required && instance===undefined){
128+
var result = new ValidatorResult(instance, schema, options, ctx);
129+
result.addError('is required, but is undefined');
130+
return result;
131+
}
127132
var result = this.validateSchema(instance, schema, options, ctx);
128133
if (!result) {
129134
throw new Error('Result undefined');

test/Validator.test.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,5 +154,25 @@ describe('Validator', function () {
154154
it('options.base must be a string', function () {
155155
validator.validate(null, true, null);
156156
});
157+
it('options.required with defined instance', function () {
158+
var res = validator.validate(undefined, true, {required: true});
159+
assert(!res.valid);
160+
console.error(res.errors);
161+
assert(res.errors[0].message.indexOf('required') >= 0);
162+
});
163+
it('options.required with undefined instance', function () {
164+
var res = validator.validate(undefined, true, {required: true});
165+
assert(!res.valid);
166+
assert(res.errors[0].message.indexOf('required') >= 0);
167+
});
168+
it('options.required is false', function () {
169+
var res = validator.validate(undefined, true, {required: false});
170+
assert(res.valid);
171+
});
172+
it('options.required defaults false', function () {
173+
// TODO DEPRECATED: this behavior changes to true in next major version
174+
var res = validator.validate(undefined, true, {});
175+
assert(res.valid);
176+
});
157177
});
158178
});

0 commit comments

Comments
 (0)