2
votes

I am using a really useful gem ClientSideValidations which works great for everything except a conditional validation where the condition is the existence of a value in another field.

I have one checkbox field (:has_dog) that if checked results in a text field (:dog_name) to be validated. Now this all works great and as expected with server-side validations however it doesn't validate when performing client-side.

Conditional validations work client-side for other fields where say I hard code true or do something else server side, however just not if the result of that needs to come from a field in the same form.

Class

class PetCare < ActiveRecord::Base
    validates :dog_name, presence: true, if: :has_dog?
end

Form

<%= form_for @pet_care, validate: true do |f| %>

   <%= f.label :has_dog %> 
   <%= f.check_box :has_dog %>

   <br />       

   <%= f.label :dog_name %>    
   <%= f.text_field :dog_name, validate: true  %>

<% end %>

So client-side "dog_name" doesn't get validated even if "has_dog" is true. (although it works server-side). I have tried every combination of names, form types and so on. It simply just does not see the "has_dog" value. I am close to just writing a custom validator for this but it seems like that would be excessive for what is a pretty simple thing. Has anyone else had this, any solutions out there?

1

1 Answers

2
votes

I hope that this helps. When I update the user model I get away with not sending the password this way.

#app/models/user.rb

class User < ActiveRecord::Base
  attr_accessor :updating_password
  def should_validate_password?
    updating_password || new_record?
  end
end

Now on the controller I have

#app/controllers/users/users_controller.rb
class Users::UsersController < UserController
  before_filter :check_password_submitted, :only => :update
  private
  def check_password_submitted
    if params[:user][:password].blank?
      params[:user].delete("password")
      params[:user].delete("password_confirmation")
      user.updating_password = false
    else
      user.updating_password = true
    end
  end
end

I know that this is not happening on the front end but it might give you a hint on what to do.

Happy Codding