Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

@validate presence #304

Closed
tdegrunt opened this Issue Jan 14, 2012 · 4 comments

Comments

Projects
None yet
2 participants
Contributor

tdegrunt commented Jan 14, 2012

There's a minor issue with @Validate presence. Say you have a User model:

class User extends Batman.Model
  firstName: null
  @validate 'firstName', presence: yes

The first time you submit, you have no firstName (it's null), you can report an error.
If the entry is blanked out somewhere during the submit process, the value of firstName is no longer null, but ''.

Fix seems (perhaps too simple?) fairly simple, including test:

diff --git a/src/batman.coffee b/src/batman.coffee
index 9a95f1a..371febe 100644
--- a/src/batman.coffee
+++ b/src/batman.coffee
@@ -3007,7 +3007,7 @@ Validators = Batman.Validators = [
     @options 'presence'
     validateEach: (errors, record, key, callback) ->
       value = record.get(key)
-      if @options.presence and !value?
+      if @options.presence and !value? or value is ''
         errors.add key, @format(key, 'blank')
       callback()
 ]

diff --git a/tests/batman/model/validations_test.coffee b/tests/batman/model/validations_test.coffee
index 5e7afd3..d611f5c 100644
--- a/tests/batman/model/validations_test.coffee
+++ b/tests/batman/model/validations_test.coffee
@@ -39,6 +39,10 @@ validationsTestSuite = ->
       p.validate (result, errors) ->
         ok !result
         QUnit.start()
+      p.set('name', '')
+      p.validate (result, errors) ->
+        ok !result
+        QUnit.start()

   asyncTest "presence and length", 4, ->
     class Product extends Batman.Model
Contributor

tdegrunt commented Jan 14, 2012

Perhaps to clarify further, I came across this when testing two fields with @Validate presence enabled.
Filling them in and clearing them in turn, turned up this error.

ktusznio commented Feb 9, 2012

I think PresenceValidator is intended to be more abstract and only test for the presence of the key. The value of the key is not examined. I think you're looking for LengthValidator which provides the minLength option:

class User extends Batman.Model
  firstName: null
  @validate 'firstName', minLength: 1
Contributor

tdegrunt commented Feb 9, 2012

Think Rails uses blank? while testing for validates presence. @validate presence: yes only tests for nil/null, not empty.

You're totally right.

@ktusznio ktusznio closed this in d5e719f Feb 10, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment