Skip to content

Instantly share code, notes, and snippets.

@g8d3
Last active June 13, 2017 16:50
Show Gist options
  • Save g8d3/f2bb4479a6244a06ed26009566d4c53e to your computer and use it in GitHub Desktop.
Save g8d3/f2bb4479a6244a06ed26009566d4c53e to your computer and use it in GitHub Desktop.
Ruby on Rails - Simple Form AJAX Validations(works with bootstrap)
removeValidations = (scope) ->
$(scope).find('.has-error .help-block').remove()
$(scope).find('.has-error').removeClass('has-error')
showValidations = (errors, scope = '') ->
for field, fieldErrors of errors
wrapper = wrapperForField(field, scope)
wrapper.addClass('has-error')
for error in fieldErrors
wrapper.append("<div class='help-block'>#{error}</div>")
wrapperForField = (field, scope = '') ->
scope += ' ' if scope[0]
$("#{scope}[name*='[#{field}]']").closest('.form-group')
# In error callback:
error: (response) ->
errors = response.responseJSON
removeValidations('.form-selector')
showValidations(errors, '.form-selector')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment