Skip to content

Instantly share code, notes, and snippets.

@milankinen
Last active December 16, 2015 22:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milankinen/5505385 to your computer and use it in GitHub Desktop.
Save milankinen/5505385 to your computer and use it in GitHub Desktop.
# PART 1: tweak backbone validation a little bit
# ===============================================
# first, allow errorous inputs to update our model
Backbone.Validation.configure
forceUpdate: true
# then disable default callbacks for backbone validation events
_.extend Backbone.Validation.callbacks,
valid: (view, attr, selector) ->
# these are not used
invalid: (view, attr, error, selector) ->
# these are not used
# we are using our custom model events "valid:<attr>" and "invalid:<attr>" to indicate
# when model field is validated
attrValid = (view, attr, selector) ->
# 'view' is not used, views use our implementation ;)
@trigger "valid:#{attr}", attr, selector
attrInvalid = (view, attr, errorMsg, selector) ->
# 'view' is not used, views use our implementation ;)
@trigger "invalid:#{attr}", attr, errorMsg, selector
origValidate = Backbone.Validation.mixin.validate
Backbone.Validation.mixin.validate = (attrs, setOptions) ->
options = setOptions || {}
# "this" refers now to model so we apply it to our validation
# functions, thus can trigger validation events for right model
options.valid = => attrValid.apply(@, arguments)
options.invalid = => attrInvalid.apply(@, arguments)
origValidate.call(@, attrs, options)
# add customized validation to our models, when validations occur, they raise
# model events valid:<attr> and invalid:<attr> to our models. Views may be interested
# in those validation callbacks for showing error messages.
_.extend(Backbone.Model.prototype, Backbone.Validation.mixin)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment