Last active
December 20, 2015 04:29
-
-
Save richsoni/6071282 to your computer and use it in GitHub Desktop.
How to render validations in the base view
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#actually renders the validations | |
#if you are using listenTo these arguments are automatically passed in | |
renderValidations: (model, errors)-> | |
_.each errors, (error) => | |
$el = if error.cid then @$("[data-id=#{error.cid}]") else @$el | |
selector = if error.nested_attr then "[data-nested-name=#{error.nested_attr}]" else "[name=#{error.name}]" | |
#validations are namespaced by model id for removal | |
$el.find(selector).after("<span class='#{model.cid}-validation label label-important'>#{error.errors.join(', ')}</span>") | |
#clears out all validations for this particular model | |
#this also needs to be called to prevent duplicate validations | |
clearValidations: -> @$(".validation").remove() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-# all regular inputs should have the attribute set as the name | |
-# nested attributes should use name as the attribute name, and the data-nested-name as the nested_attribute name | |
-# {company: {name:"x", id: 1} => name:company, data-nested-name: 1 | |
-# nested models from a collection use the data-id to filter the el | |
-# -> this means that for validations to render properly they need to be inside a container with a data-id | |
<input name='name' /> | |
<input name='company_attributes' data-nested-name='name'/> | |
<li data-id='cid'> | |
<input name="phone_numbers" data-nested-name:"country_code"/> | |
</li> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#events to listen to save and render validations | |
initialize: (args) -> | |
@listenTo(@client, 'sync', @clearValidations) | |
@listenTo(@client, 'invalid', @renderValidations) | |
#sync will run when the model is saved, if this is not enough you can manually call the function (params can be seen below) | |
#it will not be enough if validate is called and clear is not, this will render duplicate errors like (Name is required)(Name is required) | |
#invalid will run when the model is invalid, and will render the validation errors |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment