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

Rails client side validation working on submit action of all forms


I am using rails client side validations gem, version 3.2.1. Right now, I have ran in to a problem where validations are now been applied on forms where I don't want these validations to be applied.

Please find out my two forms, for sign up and sign in.

_sign_up_form.html.erb
<%= form_for(@user, :validate => true, :remote => true) do |f| %>

_sign_in_form.html.erb
<%= form_for(@user_session, :remote => true) do |f| %

As you could see i have set validate => true only on my sign up form.

I want these client side validations to be working on sign_up form and not on the sign_in form. Please note that both these forms are loaded after ajax requests made to the 'new' action of the respective controllers.

_sign_up_form.html.erb is loaded when the users/new.js.erb is rendered

*users/new/js.erb*
$("#static-form-modal .modal-body").html('<%= j(render(:partial => "users/sign_up_form"))%>');
$('form').live("click",function() {
$(this).enableClientSideValidations();
});

_sign_in_form.html.erb is loaded when user_sessions/new.js.erb is rendered

*user_sessions/new.js.erb*
$('#static-form-modal .modal-body').html('<%= j(render(:partial => "user_sessions/sign_in_form"))%>');

The client side validations are working perfect in the sign up form and the error messages are displayed next to the error fields.

The problem is that when i click the submit button of the sign in form, these validation error messages appear next to the error fields. Server side valdiations obviously, but I am not able to figure to way to remove those error messages appearing next to the error fields.

Also, i am not simple form. I have uncommented these lines in the initializers/client_side_validations.rb .

ActionView::Base.field_error_proc = Proc.new 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
  else
    %{<div class="field_with_errors">#{html_tag}</div>}.html_safe
  end
end

Any help would be greatly appreciated.


Solution

  • I am not sure whether this is right way to do so, but I checked whether the instance responds to an object_name method and changed my code accordingly.

    Please find the edited code.

    ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
      if html_tag =~ /^<label/ or instance.respond_to?(:object_name)
        %{<div class="field_with_errors">#{html_tag}</div>}.html_safe
      else
        %{<div class="field_with_errors">#{html_tag}<label for="#{instance.send(:tag_id)}" class="message">#{instance.error_message.first}</label></div>}.html_safe
      end
    end
    

    The code generated earlier could be seen in the questionare post.