diff --git a/src/locale.js b/src/locale.js index 2a413618f..32713dbea 100644 --- a/src/locale.js +++ b/src/locale.js @@ -9,6 +9,7 @@ export let mixed = { export let string = { required: '${path} is a required field', + length: '${path} must be exactly ${length} characters', min: '${path} must be at least ${min} characters', max: '${path} must be at most ${max} characters', matches: '${path} must match the following: "${regex}"', diff --git a/src/string.js b/src/string.js index 4491815ae..03489c877 100644 --- a/src/string.js +++ b/src/string.js @@ -45,6 +45,18 @@ inherits(StringSchema, MixedSchema, { ) }, + length(length, msg) { + return this.test({ + name: 'length', + exclusive: true, + message: msg || locale.length, + params: { length }, + test(value) { + return isAbsent(value) || value.length === this.resolve(length) + } + }) + }, + min(min, msg) { return this.test({ name: 'min', diff --git a/test/string.js b/test/string.js index f5ecd635e..f8d7b5121 100644 --- a/test/string.js +++ b/test/string.js @@ -168,6 +168,26 @@ describe('String types', function(){ ]) }) + it('should check LENGTH correctly', function(){ + var v = string().length(5); + var obj = object({ + len: number(), + name: string().length(ref('len')) + }) + + return Promise.all([ + v.isValid('exact').should.eventually().equal(true), + v.isValid('sml').should.eventually().equal(false), + v.isValid('biiiig').should.eventually().equal(false), + + v.isValid(null).should.eventually().equal(false), + v.nullable().isValid(null).should.eventually().equal(true), + + obj.isValid({ len: 5, name: 'foo' }).should.eventually().equal(false) + + ]) + }) + it('should validate transforms', function(){ return Promise.all([ string().trim().isValid(' 3 ').should.eventually().equal(true),