Skip to content

Commit

Permalink
can combine all the errors
Browse files Browse the repository at this point in the history
  • Loading branch information
dnagir committed Dec 22, 2011
1 parent f15eb60 commit 9497e2e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
19 changes: 13 additions & 6 deletions lib/assets/javascripts/knockout/validations.js.coffee
Expand Up @@ -12,22 +12,29 @@ class ValidationContext
me = this
dsl[name] = (fields..., options) ->
if typeof(options) is 'string'
# Last argument isn't options - it's a field
# Last argument isn't `options` - it's a field
fields.push options
options = {}
me.setValidator(func, field, options) for field in fields
dsl

setValidator: (validator, field, options) ->
me = this
me._validations ||= {}
me._validations[field] ||= []

validatorSubscriber = ko.dependentObservable ->
validator.call(me, me.subject, field, options)

validatorSubscriber.subscribe (newError) ->
me.subject.errors[field]( newError )
err = me.subject.errors[field]
me.subject.errors[field]( [err(), newError].compact().join(", ") )

# Clear the error only once before the value gets changed
validatorSubscriber.subscribe ->
me.subject.errors[field](null)
, me.subject, "beforeChange" if me._validations[field].isEmpty()

me._validations ||= {}
me._validations[field] ||= []
me._validations[field].push validatorSubscriber
me

Expand Down Expand Up @@ -56,9 +63,9 @@ ko.Validations.validators =

presence: (model, field, options) ->
val = model[field]()
isBlank = !val or (val.toString().match /^\s*$/)
isBlank = !val or val.toString().isBlank()

if isBlank then "can't be blank" else null
if isBlank then options.message || "can't be blank" else null

email: (model, field, options) ->
if model[field]()? then "should be valid email" else null
Expand Down
10 changes: 9 additions & 1 deletion spec/javascripts/knockout/validations_spec.js.coffee
@@ -1,9 +1,11 @@

class Page extends ko.Model
@fields 'name', 'correct'
@fields 'name', 'correct', 'multiple'

@validates: (me) ->
@presence 'name'
@presence 'multiple', 'multiple', 'multiple', message: 'xxx'

@custom 'correct', (page, options) ->
unless page.correct() then 'should be correct' else null

Expand All @@ -28,3 +30,9 @@ describe "Validations", ->
expect( @subject.errors.correct() ).toBeFalsy()
@subject.correct no
expect( @subject.errors.correct() ).toMatch /correct/


it "should join all the errors", ->
@subject.multiple ''
expect(@subject.errors.multiple()).toBe "xxx, xxx, xxx"

0 comments on commit 9497e2e

Please sign in to comment.