From 5a8649de5270854d888221e01274b501827b6702 Mon Sep 17 00:00:00 2001 From: Austin Wright Date: Mon, 19 Oct 2020 18:44:36 -0700 Subject: [PATCH] Validator#validate: add "required" option --- lib/helpers.js | 1 + lib/validator.js | 5 +++++ test/Validator.test.js | 20 ++++++++++++++++++++ 3 files changed, 26 insertions(+) diff --git a/lib/helpers.js b/lib/helpers.js index 2254baa..d0a3529 100644 --- a/lib/helpers.js +++ b/lib/helpers.js @@ -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 = []; diff --git a/lib/validator.js b/lib/validator.js index 7961344..c99904c 100644 --- a/lib/validator.js +++ b/lib/validator.js @@ -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'); diff --git a/test/Validator.test.js b/test/Validator.test.js index 0f5edc1..d5f5b29 100644 --- a/test/Validator.test.js +++ b/test/Validator.test.js @@ -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); + }); }); });