Client side validation is not working while applying conditional validation in rails 4

StackOverflow https://stackoverflow.com/questions/22906257

  •  28-06-2023
  •  | 
  •  

Pergunta

I am using client side validation gem. Client side validation is not working while applying conditions. Here is my Model Class.

validates_uniqueness_of :project_code
**validates :price, numericality: true, :if => :project_type_fixed?**

def project_type_fixed?
  project_type == 'Fixed'
end

In this code validation for project_code is working fine, but for price it is not working. Thanks in advance.

Foi útil?

Solução

Client_side_validations does not validate conditionals out-of-the-box. What you are observing is the intended behavior.

In order to validate conditionals, you need to force them in your form:

f.number_field :price, :validate => { :numericality => true}

In addition, according to the documentation, the value needs to evaluate to true at the time the form is being generated. However, there is a hack for this: The method that determines whether the condition evaluates to true is called run_conditional (source), so you can override that method in your model:

def run_conditional(method_name_value_or_proc)
  (:project_type_fixed? == method_name_value_or_proc) || super
end
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top