Script to Make Client Side Validations Work w/ Twitter Bootstrap & Simple Form

  • Download Gist
ClientSideValidations_TwitterBoostrap_SimpleForm.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
(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();
}
};

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/

If you want to use this with current stable version of client side validations (3.1.4)
You have to change this line
ClientSideValidations.formBuilders['SimpleForm::FormBuilder']
to
clientSideValidations.formBuilders['SimpleForm::FormBuilder']

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?

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.