【问题标题】:Custom validator in client_side_validationsclient_side_validations 中的自定义验证器
【发布时间】:2012-05-11 11:40:59
【问题描述】:

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

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)

【问题讨论】:

    标签: ruby-on-rails-3 client-side-validation custom-validators


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-15
      • 1970-01-01
      • 1970-01-01
      • 2014-01-02
      • 2019-01-07
      相关资源
      最近更新 更多