diff --git a/lib/validation/validators.js b/lib/validation/validators.js index a747961..9330b5a 100644 --- a/lib/validation/validators.js +++ b/lib/validation/validators.js @@ -35,6 +35,12 @@ let validators = { return validators.string(value) && (value === '' || value.length <= length); }, + maxwords(text, length) { + if (!validators.string(text)) return false; + const words = text.match(/\S+/g) || []; + return words.length <= length; + }, + exactlength(value, length) { return validators.string(value) && (value === '' || value.length === length); }, diff --git a/test/validation/spec.validators.js b/test/validation/spec.validators.js index c0809d1..fb7565c 100644 --- a/test/validation/spec.validators.js +++ b/test/validation/spec.validators.js @@ -163,6 +163,37 @@ describe('validators', () => { }); + describe('maxwords', () => { + + describe('invalid values', () => { + let inputs = [ + [undefined, 1], + [100, 10], + ['asdfasdfasdf', 0], + ['asdf asdf asdf asdf asdf asdf asdf asdf', 3] + ]; + _.each(inputs, i => { + it(testName(i), () => { + validators.maxwords.apply(null, i).should.not.be.ok; + }); + }); + }); + + describe('valid values', () => { + let inputs = [ + ['', 0], + ['asdfasdf asdf asdf asdf asdf', 10], + ['123', 4] + ]; + _.each(inputs, i => { + it(testName(i), () => { + validators.maxwords.apply(null, i).should.be.ok; + }); + }); + }); + + }); + describe('exactlength', () => { describe('invalid values', () => {