Search code examples
ruby-on-railsvalidationclient-side-validation

Adding client side validations to modal using 'bootstrap_form' gem


I am trying to integrate client side validations into my rails app. I need the validations to appear in the modal. I am currently using this gem for the forms:

https://github.com/bootstrap-ruby/rails-bootstrap-forms

I cannot get the validations to work, and believe I am either setting it up incorrectly, or need to use different tools. If anyone could advise, I would appreciate it.

Here is an example of a form:

HTML

<div id="signupmodal" class="modal fade" tabindex="-1" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">×</button>
                  <h3 class="">Sign Up</h3>
            </div>
            <div class="modal-body">
              <%= bootstrap_form_for :new_user, :html => {:id => 'new_user'}, url: users_path do |f| %>
              <%= f.text_field :name, hide_label: true, placeholder: "Enter Your Name", icon: "tag", :class => "input-lg required" %>
              <%= f.text_field :email, hide_label: true, placeholder: "Enter Your Email", icon: "user", :class => "input-lg required" %>
              <%= f.password_field :password, :html => {:id =>'user_signup_password'}, hide_label: true, placeholder: "Enter Your Password", icon: "lock", :class => "input-lg required" %>
              <%= f.password_field :password_confirmation, hide_label: true, placeholder: "Confirm Your Password", icon: "lock", class: "input-lg required"%>
              <%= f.submit "Signup", class: "btn btn-primary btn-lg btn-block signup-submit" %>
              <% end %>
              <div class="text-center signup-or"> OR </div>
              <%= link_to 'Signup with Facebook', '/auth/facebook', :class => 'btn btn-primary btn-lg btn-block' %>
            </div>
        </div>
    </div>
</div>

User Model

class User < ActiveRecord::Base
  has_secure_password

  before_create :confirmation_token

  belongs_to :state
  belongs_to :country
  belongs_to :account_type

  has_many :authentications

  validates :email,
    presence: true,
    uniqueness: {case_sensitive: false},
    format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create }

  validates :password, :presence =>true, :confirmation =>true
  validates_confirmation_of :password
end

Solution

  • For client side validations you will need Javascript. Client side validation entails that a validation occurs BEFORE it hits the server, the validations you have setup are Rails validations and those occur AFTER the form has been submitted. If you want to validate a form before it is submitted I recommend a Jquery plugin such as http://jqueryvalidation.org/ . Adding Jquery validation to your project will allow you to check your forms before they are submiited to the server.