0

我需要添加自定义验证器来比较两个日期 - 开始日期和结束日期。我创建了自定义验证器

class MilestoneDatesValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    if record.start_date > record.end_date
      record.errors.add(attribute, :end_date_less, options.merge(:value => value))
    end
  end
end

我创建了 ClientSideValidations 自定义验证器。我不确定如何在其中获取其他属性值,但我尝试以这种方式执行此操作:

ClientSideValidations.validators.local['milestone_dates'] = function(element, options) {
  start_date = new Date($('#milestone_start_date').val());
  end_date = new Date($('#milestone_end_date').val());
  if(end_date < start_date) {
    return options.message;
  }
}

但它不起作用/我只有在重新加载页面后才会出现错误,而不是客户端验证。我使用 client_side_validations (3.2.0.beta.3)、client_side_validations-formtastic (2.0.0.beta.3)、rails (3.2.3)

4

1 回答 1

1

您在上面提供的代码没有提及验证器辅助方法的声明(和使用)。在milestone_dates_validator.rb 初始化程序中,尝试在文件末尾添加以下内容:

module ActiveModel::Validations::HelperMethods
  def validates_milestone_dates(*attr_names)
    validates_with MilestoneDatesValidator, _merge_attributes(attr_names)
  end
end

并在您的模型中调用您正在验证的属性上的验证器:

validates_milestone_dates :milestone_ends_at
于 2012-06-18T00:24:38.763 回答