我需要添加自定义验证器来比较两个日期 - 开始日期和结束日期。我创建了自定义验证器
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形式(2.0.0.beta.3),轨道(3.2.3)
您在上面提供的代码缺少对验证程序帮助程序方法的声明(和使用)的任何提及。在 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