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

笑着哭i 提交于 2019-12-20 05:41:50

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/22906257/client-side-validation-is-not-working-while-applying-conditional-validation-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!