Shopify/batman — Issue #304: @validate presence
Author: tdegrunt
Created: 2012-01-14 16:41:17+00:00
State: open

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