Permalink
Browse files

adding length validation and allow blank to format

  • Loading branch information...
1 parent e2908b3 commit ce385bc041a54d1c64001ba9a069c056aa733686 @superchris superchris committed Nov 1, 2012
@@ -8,6 +8,17 @@ describe "validation", ->
last_name:
format:
with: "/^S.*/"
+ message: "Hey, you suck!"
+ uniqueness:
+ case_sensitive: true
+ other_field:
+ format:
+ with: "/^K.*/"
+ allow_blank: true
+ phone:
+ length:
+ minimum: 7
+ maximum: 10
@model = new BoringModel
@validationErrors = {}
@model.on "error", (model, errors) =>
@@ -29,10 +40,27 @@ describe "validation", ->
@model.set last_name: "Not smith"
it "should validate format", ->
expect(@validationErrors.last_name.length).toEqual 1
+ it "should use the mesage", ->
+ expect(@validationErrors.last_name[0]).toMatch /suck/
describe "when matching", ->
beforeEach ->
@model.set last_name: "Smith"
it "should validate format", ->
expect(@validationErrors.last_name).not.toBeDefined()
+ describe "when blanks are allowed", ->
+ beforeEach ->
+ @model.set other_field: ""
+ it "allows blanks", ->
+ expect(@validationErrors.other_field).not.toBeDefined()
-
+ describe "length", ->
+ describe "when not matching", ->
+ beforeEach ->
+ @model.set phone: "1"
+ it "should have errors on phone", ->
+ expect(@validationErrors.phone.length).toEqual 1
+ describe "when matching", ->
+ beforeEach ->
+ @model.set phone: "1234567"
+ it "should not have errors on phone", ->
+ expect(@validationErrors.phone).not.toBeDefined()
@@ -1,13 +1,19 @@
Backtastic.Validators =
presence: (options) ->
- (field, value) -> "is required" unless value?.length > 0
+ message = options.message || "is required"
+ (field, value) -> message unless value?.length > 0
format: (options) ->
+ message = options.message || "must match specified format"
toRegExp = (str) ->
new RegExp(str.replace(/^\//, "").replace(/\/$/, ""))
pattern = if _.isRegExp(options?.with) then options?.with else toRegExp(options?.with)
- (field, value) -> "must match specified format." unless value?.match(pattern)
+ (field, value) -> message unless value?.match(pattern) or (options.allow_blank and _.isEmpty(value))
+
+ length: (options) ->
+ message = options.message || "must be between #{options.minimum} and #{options.maximum} characters"
+ (field, value) -> message unless Number(options.minimum) <= value.length <= Number(options.maximum)
Backtastic.Validation =
@@ -16,7 +22,8 @@ Backtastic.Validation =
addValidator: (validator, field, options) ->
@validations or = {}
@validations[field] or= []
- @validations[field].push Backtastic.Validators[validator]?(options)
+ validator = Backtastic.Validators[validator]?(options)
+ @validations[field].push validator if validator
validatePresenceOf: (field) ->
@addValidator("presence", field)

0 comments on commit ce385bc

Please sign in to comment.