Ruby on Rails Client Side Validation with Validation Helpers and Twitter Bootstrap

[Edit: March 3, 2013 - The script I have below to get client side validations working with Twitter Bootstrap is no longer need with a recent version of the client_side_validations-simple_form gem. The following gem configuration should work just fine (later versions should be fine too):

gem 'simple_form', '2.0.4'
gem 'client_side_validations', '3.2.1'
gem 'client_side_validations-simple_form', '2.0.1'

Be sure to preserver the order. You'll also need to add "//= require rails.validations.simple_form" right after "//= require rails.validations" in your appication.js file. See gem's github page for more info. Thanks to Chris Beck for the heads up on this. - Darren  Smith]

I’ve been keeping an eye for a good client side validation gem that works with Twitter Bootstrap and allows you to use Rail’s model validation helpers. While I haven’t found a gem that combines those things, I have found a solution. You’ll need Twitter Bootstrap 2, SimpleForm 2.0, and Client Side Validations 3.2.0.beta.3. The versions are important. It is possible that this solution will work with different versions, but the versions stated have been tested. I’ll assume you already have Twitter Bootstrap installed or at least know how it to. If not, please visit http://twitter.github.com/bootstrap/ or install via a gem which you can find here. Next, add the following two lines to your gem file and run bundle install.

gem 'client_side_validations', '3.2.0.beta.3', :git => 'https://github.com/bcardarella/client_side_validations.git'
gem 'simple_form', '2.0'

You’ll now need to run generator commands for both gems:

Simple Form (the bootstrap option refers to Twitter Bootstrap)

rails generate simple_form:install --bootstrap

Client Side Validations

rails g client_side_validations:install

Next you’ll want to add validations script to the application.js file so that it can be loaded. Do this before the //= require_tree . entry.

//= require rails.validations

Now you’ll need to add a special script to get Client Side Validations to work with Twitter Bootstrap. I got this script from some comments on an issue of Client Side Validations on Github. You can add this script to your javascripts folder and name it whatever you like. The script does use jQuery, so that’ll be required to use the script as-is. For different application.js setups, just make sure that this script will get executed after rails.validations.

(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();
  }
};

Now you should be all set up to start creating forms using SimpleForm, Twitter Bootstrap, and Client Side Validations. When creating a form you need to pass in :validate => true to the simple_form_helper.

<%= simple_form_for @car, :validate => true  do |f| %>

To see all of this in action clone my example project on github.

I hope this helps anyone who was in the same predicament as me… wanting to do client-side validations using Rails model validators with Twitter Bootstrap. The information from this post was pulled together from comments on an issue from the Client Side Validations Github site. I know this isn’t the perfect solution, but it does work, contributes to a good user experience, and keeps code DRY.

This entry was posted in Ruby on Rails, User Experience. Bookmark the permalink.

18 Responses to Ruby on Rails Client Side Validation with Validation Helpers and Twitter Bootstrap

  1. Jason says:

    Woohoo! That worked. Thanks for the writeup, Darren.

  2. Darren says:

    @Jason, glad to help!

  3. Andrea says:

    Thanks a lot for the article. It works!

  4. M.Umesh says:

    hi glad to see this helpline..it works on localserver, But not in heroku server. Do you have any solution.???

  5. Santiago says:

    Thank you a lot! It simply works!

  6. Faruk says:

    Thanks Darren;
    I like the green borders :)

  7. saurabh says:

    Many thanks for this solution!

  8. umesh says:

    thank you for ur instructions. Now i initiated a project and i’ve done as u said above. But, it says, only ’3.2.0.beta.6′ is available to install. Ater installed this version, i tried, and it again says that
    TypeError: settings is undefined
    return $(this).isValid(settings.validators);
    this javascript error.
    Do you have any solution for this?

  9. If you want to use this with current stable version of client side validations (3.1.4)

    $ bundle

    Using client_side_validations (3.1.4)
    Using simple_form (2.0.2)

    You have to change this line
    ClientSideValidations.formBuilders['SimpleForm::FormBuilder']
    to
    clientSideValidations.formBuilders['SimpleForm::FormBuilder']

  10. Faraz says:

    Is there any way to do this w/o using SimpleForm? In my project, I’m just using form_for.

    Thanks in advance!

  11. Keil Miller says:

    Thank you @Darren, and thank you @Phillip Vieira for the edit to make it work with the stable release! It worked perfectly! This should be added to the gem, maybe as a generator.

  12. Chris Beck says:

    I was able to get everything working out of the box with


    gem 'simple_form', '2.0.4'
    gem 'client_side_validations', '3.2.1'
    gem 'client_side_validations-simple_form', '2.0.1'

    The order matters

  13. Prasad Surase says:

    I m using the specified gems for an application.
    1) rails 3.2.9
    2) mongoid (3.0.14)
    3) mongoid-paperclip (0.0.8)
    4) client_side_validations (3.2.1)
    5) client_side_validations-mongoid (3.0.1)
    6) client_side_validations-simple_form (2.0.1)
    7) remotipart (1.0.2) #for image upload using remote form.

    The problem is that the form gets submitted(remote) even if values for necessary fields aren’t specified. ie. CSV doesn’t work. Any suggestions?

  14. Montoo says:

    Good stuff… I found your post 5 minutes after I followed the steps to get the Client_side_validations, simple_form, turbolinks combination to work. When the stuff did not work, I figured that bootstrap has to be the missing piece of the puzzle…

    thanks @Darren, and thanks @Phillip Vieira…

    you guys rock.

  15. ben radler says:

    I’m trying to get this set up on my site — the validation errors DO show up when focusing/blurring an , but the errors appear outside of the element, at the bottom of the page. Any idea why this might happen?

    I also notice that my isn’t being wrapped in a div.control-group, as your example site is.

    using these gems:

    gem 'simple_form', '2.1.0'
    gem 'client_side_validations', '3.2.5'
    gem 'client_side_validations-simple_form', '2.1.0'

  16. This lake in Rocky Mountain National Park commemorates the work of German artist Albert Bierstadt, whose paintings include many scenes of the American West. This short trail switchbacks up to scenic Bierstadt Lake and is one of several ways to reach the lake. In winter, be careful to stay on the trail because deep snow can often obscure it. If you’re lucky, you will encounter some wildlife, which roam freely and without fear in Rocky Mountain National Park. Snowshoers will likely enjoy this trail more than nordic skiers due to the steep, narrow switchbacks.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>