Permalink
Browse files

can combine all the errors

  • Loading branch information...
1 parent f15eb60 commit 9497e2e8639f135961fe8552062a903ddc88699f @dnagir committed Dec 22, 2011
@@ -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
@@ -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
@@ -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
@@ -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.