Skip to content

Commit

Permalink
Merge pull request #67 from jcsmesquita/master
Browse files Browse the repository at this point in the history
Added ability to validate string with exact length.
  • Loading branch information
jquense authored May 4, 2017
2 parents ce5864f + 4e0d919 commit 91e077b
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/locale.js
Original file line number Diff line number Diff line change
Expand Up @@ -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}"',
Expand Down
12 changes: 12 additions & 0 deletions src/string.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
20 changes: 20 additions & 0 deletions test/string.js
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down

0 comments on commit 91e077b

Please sign in to comment.