From 6b665b84f8416051697400ab301d404a66b6444a Mon Sep 17 00:00:00 2001 From: Gleb Bahmutov Date: Mon, 30 Apr 2018 15:02:50 -0400 Subject: [PATCH 1/2] fix: handle custom formats with null values --- index.js | 4 ++-- test/misc.js | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index 1ec896d..50f2bf4 100644 --- a/index.js +++ b/index.js @@ -212,7 +212,7 @@ var compile = function(schema, cache, root, reporter, opts) { } if (node.format && fmts[node.format]) { - if (type !== 'string' && formats[node.format]) validate('if (%s) {', types.string(name)) + if (type !== 'string' && fmts[node.format]) validate('if (%s) {', types.string(name)) var n = gensym('format') scope[n] = fmts[node.format] @@ -220,7 +220,7 @@ var compile = function(schema, cache, root, reporter, opts) { else validate('if (!%s.test(%s)) {', n, name) error('must be '+node.format+' format') validate('}') - if (type !== 'string' && formats[node.format]) validate('}') + if (type !== 'string' && fmts[node.format]) validate('}') } if (Array.isArray(node.required)) { diff --git a/test/misc.js b/test/misc.js index 4ea36d5..01db23e 100644 --- a/test/misc.js +++ b/test/misc.js @@ -237,6 +237,24 @@ tape('custom format', function(t) { t.end() }) +tape('custom format string or null', function (t) { + var validate = validator({ + type: 'object', + properties: { + foo: { + type: ['string', 'null'], + format: 'as' + } + } + }, {formats: {as:/^a+$/}}) + + t.notOk(validate({foo:''}), 'not as') + t.notOk(validate({foo:'bar'}), 'not as') + t.ok(validate({foo:'a'}), 'as') + t.ok(validate({foo:null}), 'as') + t.end() +}) + tape('custom format function', function(t) { var validate = validator({ type: 'object', From aad34be384ae86be741cd280f34bb22479abe61a Mon Sep 17 00:00:00 2001 From: Gleb Bahmutov Date: Tue, 1 May 2018 09:40:59 -0400 Subject: [PATCH 2/2] confirm custom format does not pass non-string --- test/misc.js | 1 + 1 file changed, 1 insertion(+) diff --git a/test/misc.js b/test/misc.js index 01db23e..a35a375 100644 --- a/test/misc.js +++ b/test/misc.js @@ -250,6 +250,7 @@ tape('custom format string or null', function (t) { t.notOk(validate({foo:''}), 'not as') t.notOk(validate({foo:'bar'}), 'not as') + t.notOk(validate({foo:123}), 'not as if number') t.ok(validate({foo:'a'}), 'as') t.ok(validate({foo:null}), 'as') t.end()