Gem client_side_validations 自定义 js 验证的问题

kikyous · 2013年06月17日 · 最后由 zuozuo 回复于 2013年06月18日 · 3343 次阅读

hi, 我现在有个问题: form 有两个字段 a 和 b 现在要验证 a 的值必需小于 b 的值。

在 model 层自定义的 validater 在浏览器端不起作用。

validate :my_validate
def my_validate
  if a >= b
    errors.add(:a,"a的值必需小于b")
  end
end

这个该怎么办?

去看 client_side_validation 在 github 上面的 README 中 conditional validation 部分的说明。

#1 楼 @zuozuo 能详细一点吗,我还是不知道改怎么做

By default conditional validators are not evaluated and passed to the client. We do this because the state model when the form is rendered is not necessarily the state of the model when the validations fire server-side. However, if you wish to override this behavior you can do so in the form. Given the following model:

class Person < ActiveRecord::Base
  validates :name, :email, :presence => true, :length => { :maximum => 10 }, :if => :can_validate?

  def can_validate
    true
  end
end

You can force in the form:

<%= f.text_field :name, :validate => true %>

Passing :validate => true will force all the validators for that attribute. If there are conditionals they are evaluated with the state of the model when rendering the form

也就是说默认情况下条件验证是不会直接执行并传递给客户端(也就是你的 view 中 form 部分的代码),那如果你想让你自己写得条件验证生效的话,你就需要在表单代码里加入 :validate => true, 具体请参考上面的示例代码。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号