The Railscast for the Client Side Validations Gem is very outdated and does not function. Furthermore, the documentation for the gem did not completely work with my version of Rails, 3.2.13. The point of this post is to get front end validations to work with Rails 3.2.13.
gem ‘client_side_validations’
$ rails g client_side_validations:install
The file below is created, but you must uncomment lines 10 through 16 in order to get it to work.
config/initializers/client_side_validations.rb
12345678910111213141516
# ClientSideValidations Initializer# Uncomment to disable uniqueness validator, possible security issue# ClientSideValidations::Config.disabled_validators = [:uniqueness]# Uncomment to validate number format with current I18n locale# ClientSideValidations::Config.number_format_with_locale = true# Uncomment the following block if you want each input field to have the validation messages attached.ActionView::Base.field_error_proc=Proc.newdo|html_tag,instance|unlesshtml_tag=~/^<label/%{<div class="field_with_errors">#{html_tag}<label for="#{instance.send(:tag_id)}" class="message">#{instance.error_message.first}</label></div>}.html_safeelse%{<div class="field_with_errors">#{html_tag}</div>}.html_safeendend
//= require rails.validations ...in applications.js ...and the following to your form.
Your app should now be able to display Rails error messages in line with your form fields. This is where I began to run into problems, creating a custom validator.
The Github Documentation says to put the following code into app/validators/email_validator.rb
initializers/email_validator.rb
1234567891011121314
classEmailValidator<ActiveModel::EachValidatordefvalidate_each(record,attr_name,value)unlessvalue=~/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/irecord.errors.add(attr_name,:email,options.merge(:value=>value))endendend# This allows us to assign the validator in the modelmoduleActiveModel::Validations::HelperMethodsdefvalidates_email(*attr_names)validates_withEmailValidator,_merge_attributes(attr_names)endend
This did not work for me. However, creating the email_validator.rb file under the initializers directory did the trick. I need to ask a Flatiron School compadre why this is. Follow the rest of the custom validator documentation for awesome validations. I hope this saves people time while implenting this gem.