Skip to content

Instantly share code, notes, and snippets.

@developwithpassion
Created October 18, 2013 19:13
Show Gist options
  • Save developwithpassion/7046598 to your computer and use it in GitHub Desktop.
Save developwithpassion/7046598 to your computer and use it in GitHub Desktop.
Hey guys, this is a spike I threw together for validation. Thoughts, comments?
ValidationRule = Ember.Object.extend
description: null
constraint: null
validate: (target) ->
return @constraint.call(target)
ValidationResult = Ember.Object.extend
successfulRules: []
brokenRules: []
allSucceeded: ->
@brokenRules.length == 0
hasFailures: ->
! @allSucceeded()
Validator = Ember.Mixin.create
validationRules: []
addRule: (details) ->
@validationRules.push ValidationRule.create
description: details.description,
constraint: details.constraint
validatesPresenceOf: (attribute) ->
@addRule
description: "The #{attribute} is required",
constraint: Check.that(attribute).notNullOrEmpty()
validatesMinimumLengthOf: (attribute, minimum) ->
@addRule(
description: "The #{attribute} needs to be a minimum of #{length} character long",
constraint: Check.that(attribute).matches -> this.length >= minimum
)
validate: (target) ->
brokenRules = []
successfulRules = []
for rule in @get('validationRules')
ruleSet = if (rule.validate(target)) then successfulRules else brokenRules
ruleSet.push rule
return ValidationResult.create(
brokenRules: brokenRules,
successfulRules: successfulRules)
Validatable = Ember.Mixin.create
validate: ->
@validator.create().validate(this)
AttributeConstraintBuilder = (name) ->
name: name
matches: (constraint) ->
name = @name
return ->
attributeValue = this[name]
return constraint.call(attributeValue)
notNullOrEmpty: ->
validation = ->
return this != null && this.trim() != ""
return @matches(validation)
Check =
that: (field) ->
return new AttributeConstraintBuilder(field)
PersonValidator = Ember.Object.extend(Validator,
validations: ( ->
@validatesPresenceOf 'name'
@validatesMinimumLengthOf 'name', 20
).on('init')
)
Person = Ember.Object.extend(Validatable,{
name: null
validator: PersonValidator
})
describe "Person Validations", ->
Given ->
@sut = Person.create()
describe "A person without a name should not be valid", ->
Given ->
@sut.name = ""
When ->
@result = @sut.validate()
Then ->
expect(@result.allSucceeded()).toBe(false)
describe "A person with a name that does not meet the minimum length is not valid", ->
Given ->
@sut.name = "Hello There"
When ->
@result = @sut.validate()
Then ->
expect(@result.allSucceeded()).toBe(false)
describe "A person with a name that meets the minimum lengths is valid", ->
Given ->
@sut.name = "A Name That Meets The Minimum Length"
When ->
@result = @sut.validate()
Then ->
expect(@result.allSucceeded()).toBe(true)
@stevemadere
Copy link

Is Check ever used in any other way than "Check.that" ?

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