Real Time Client Side Validations

This tutorial will explain how to enable real time validations when filling out a form.

Every Rails application should have validations put in place inside a model whenever dealing with forms. For example, when validating the exact length of a field you could use something like this:

validates :date, length: { is: 10 }

The problem with this is that these validations are only checked when the form submit button is pressed, not in real time when the user is filling out each field. To combat this issue, we can use the client_side_validations gem. This allows for real time checking of validations located in the model.

To get started, add this line to your Gemfile:

gem 'client_side_validations'

Then run bundle install and then rails g client_side_validations:install

This will create the config/initializers/client_side_validations.rb file. Inside this file will be some commented out code. Read this code and decide what to uncomment. Inside my client_side_validations.rb file I have uncommented this section:

ActionView::Base.field_error_proc = do |html_tag, instance|
   unless html_tag =~ /^<label/
     %{<div class="field_with_errors">#{html_tag}<label for="#{instance.send(:tag_id)}" class="message">#{instance.error_message.first}</label></div>}.html_safe
     %{<div class="field_with_errors">#{html_tag}</div>}.html_safe

Next you need to add this line to the /assets/javascripts/application.js before the //= require_tree . line and after the //= require turbolinks line:

//= require rails.validations

Next you need to modify your form. You can use the default Rails form, or Simple Form, whichever you prefer.

<%= form_for @booking, validate: true do |f| %>
# Or
<%= simple_form_for @booking, validate: true do |f| %>

Remember, if you do not have any validations in the model, this will not work. Also, if you want to style the error messages, modify the CSS for the following classes:

Once this is all done, try to fill out a form field incorrectly and you will see inline, real time error messages.

Client Side Validation

Last post: March 16, 2017 :: © bytcode 2017 :: contact