Created
May 15, 2012 21:35
-
-
Save ddarren/2705324 to your computer and use it in GitHub Desktop.
Script to Make Client Side Validations Work w/ Twitter Bootstrap & Simple Form
This file contains 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
(function() { | |
$(document).ready(function() { | |
return $("div.control-group").focusout(function() { | |
if (!$("div.control-group").hasClass("error")) { | |
return $(this).addClass("success"); | |
} | |
}); | |
}); | |
}).call(this); | |
ClientSideValidations.formBuilders['SimpleForm::FormBuilder'] = { | |
add: function(element, settings, message) { | |
var errorElement, wrapper; | |
settings.wrapper_tag = ".control-group"; | |
settings.error_tag = "span"; | |
settings.error_class = "help-inline"; | |
settings.wrapper_error_class = "error"; | |
settings.wrapper_success = "success"; | |
if (element.data('valid') !== false) { | |
wrapper = element.closest(settings.wrapper_tag); | |
wrapper.removeClass(settings.wrapper_success); | |
wrapper.addClass(settings.wrapper_error_class); | |
errorElement = $("<" + settings.error_tag + "/>", { | |
"class": settings.error_class, | |
text: message | |
}); | |
return wrapper.find(".controls").append(errorElement); | |
} else { | |
wrapper = element.closest(settings.wrapper_tag); | |
wrapper.addClass(settings.wrapper_error_class); | |
return element.parent().find("" + settings.error_tag + "." + settings.error_class).text(message); | |
} | |
}, | |
remove: function(element, settings) { | |
var errorElement, wrapper; | |
settings.wrapper_tag = ".control-group"; | |
settings.error_tag = "span"; | |
settings.error_class = "help-inline"; | |
settings.wrapper_error_class = "error"; | |
settings.wrapper_success = "success"; | |
wrapper = element.closest("" + settings.wrapper_tag + "." + settings.wrapper_error_class); | |
wrapper.removeClass(settings.wrapper_error_class); | |
wrapper.addClass(settings.wrapper_success); | |
errorElement = wrapper.find("" + settings.error_tag + "." + settings.error_class); | |
return errorElement.remove(); | |
} | |
}; |
You might also need to change the name of the formBuilder
if you subclass CustomFormBuilder < SimpleForm::FormBuilder
Thank you for this!
Does this work for Bootstrap 3?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you so much! It worked perfectly!
As per comment on this blog post: http://www.ddarrensmith.com/blog/2012/05/17/ruby-on-rails-client-side-validation-with-validation-helpers-and-twitter-bootstrap/