rigelstpierre
rigelstpierre

Reputation: 544

Client Side Validation Gem Not Working

I'm using client side validations gem for a form on a coming soon page and no matter what I've done I can't get the form to show the validations.

Here is the form

<%= form_for @user, :remote => true, :validate => true do |f| %>
  <% @user.errors.full_messages.each do |msg| %>
      <p><%= msg %></p>
    <% end %>

  <%= f.text_field :username, :placeholder => "Username" %>
  <%= f.email_field :email, :placeholder => "Email" %>
  <button class="btnSmall" type="submit" name="commit" type="submit" value="Create User"><img  src="/assets/arrowWhite.png" alt="Submit Credentials" /></button>

  <button class="btnLarge" type="submit" name="submit">Submit<img class="arrowWhite1x" src="/assets/arrowMobileWhite.png" alt="Submit Credentials" /><img class="arrowWhite2x" src="/assets/[email protected]" /><</button>

<% end %>

I'm loading sending the form via AJAX and so I'm also loading the validations via JS like this

$(document).ready ->
  $('#new_user').enableClientSideValidations()

This is my model

class User < ActiveRecord::Base
  attr_accessible :email, :username

  validates_uniqueness_of :username, :email
  validates :email, :email_format => true
end

Upvotes: 2

Views: 1402

Answers (1)

0x4a6f4672
0x4a6f4672

Reputation: 28245

I had a similar problem: no errors in the JS console, it simply did not work - no validation, no message, nothing. I could get it to work temporarily if I called $('form').enableClientSideValidations() or $('form[data-validate]').validate(); manually from the JS console.

It turned out that the ClientSideValidation gem does not work if the form is hidden. The functions resetClientSideValidations() or enableClientSideValidations() have to be called after the form has been made visible. If they are called before, when the form is still hidden, they have no effect.

$('form').enableClientSideValidations();  # works only if form visible

Other reasons why the gem would not work are version conflicts, have you tried to update the gems, to run the generators with rails g client_side_validations:copy_assets, and to add the javascript references to your application.js?

If it is a dynamic form, one could try

$('form[data-validate]').validate();

see here

Upvotes: 2

Related Questions