JRL About

Simple Forms Client Validation in Rails 5

July 17, 2017
Updated: November 30, 2021

Twitter Hacker News Reddit LinkedIn
Article Header Image
U

tilizing validation ensures good data integrity. You should validate on the server (in the model/controller) for security, and on the client to improve the user experience. It is very simple to set up in rails with the client_side_validations gem.

Also, despite the rumors the gem is actively maintained.

Basic Setup

First, add the simple form, validation, and jquery gems to your Gemfile then bundle install. According to the README, order matters.

1
2
3
4
gem 'jquery-rails'
gem 'simple_form'
gem 'client_side_validations'
gem 'client_side_validations-simple_form'

Modfiy your app/assets/javascripts/application.js to import the JS logic. Order definitely matters.

1
2
3
4
//= require jquery
//= require jquery_ujs
//= require rails.validations
//= require rails.validations.simple_form

Generate the intializer logic via rails g client_side_validations:copy_assets. You can then view the initializer config file at config/initializers/client_side_validations.rb.

Open up your simple form and add validate: true:

1
2
3
4
<%= simple_form_for @event, validate: true do |f| %>
  <%= f.input :name %>
  <%= f.button :submit %>
<% end %>

Finally, add some validation to your model. The following code ensures :name is present and cannot be an empty string.

1
2
3
class Event < ApplicationRecord
    validates :name, presence: true, allow_blank: false
end

That's it! Now fields can be validated on the client instead of forcing the user to submit the form first.

jQuery

Not everyone wants jQuery in their app, but the cost of re-writing your own verification logic is likely greater than the cost due to including jQuery. Modern minified jQuery is 84kb, smaller than a small image, and is virtually guaranteed to already be cached on a given client's device.