Client Side Validations 3.0 is out! Adding client side validations to an existing Rails 3 project is as simple as: (assuming you are already using jQuery >= 1.4.1)
# Your Gemfile gem 'client_side_validations'
rails g client_side_validations:install
And it works! Wait… you don’t see anything?
Okay, so by default ActionView::Base.field_error_proc will wrap invalid fields with a ‘field_with_error’ class div. We need to extend this to also show the error message. The generator added config/initializers/client_side_validations.rb You need to uncomment the ActionView::Base.field_error_proc override. Now restart your rails app and presto-changeo you’ve got client side validations!
Let’s take a step back and look at the goals of this gem:
Breaking these down…
As Luke points out in his blog post Live Validations (or client side validations) are great for increasing conversion rates. He details how validating after a user exits a field yields the highest conversion rates (as well as the least confusion). Client Side Validations follows this philiosophy.
ActiveModel in Rails 3 allows us to reflect upon a given model’s validations. Client Side Validations takes advantage of this to package the rules and i18n messages for use on the client.
Some validations don’t make sense to attempt on the client. Instead of trying to get around this ClientSideValidations ignores these cases with the assumption the server will always be able to handle it better.
Considering that we’re allowing some validations to pass to the server we need to ensure that how the errors render on a server side must match exactly how the errors render on the client side. To this end Client Side Validations uses the power of jQuery to properly render the error for a given FormBuilder.
As long as your model is using ActiveModel::Validations it should work. This includes ActiveRecord 3, Mongoid 2.0. MongoMapper is in the process of adopting ActiveModel.
If your forms have nested fields via field_for all validations should apply without any issue.
If you write your own validations they are fully supported with just a small amount of code. The Wiki has a detailed guide on how to add custom validator support
Client Side Validations support SimpleForm and Formtastic. Most of the customization options should also be supported. Your own custom FormBuilder can be supported too, look out for a guide on the wiki soon.
Control the behavior of how the error messages appear or how a form handles failing validation with callbacks. The Wiki has a detailed guide on the callbacks
I hope people enjoy using this library. The re-write has taken a few months of my time and I’m happy to share the work with everybody. If you have any issues at all please don’t hesitate to open an Issue on Github or contact me with any questions!