Question

I need to add custom validator for comparing two dates - start date and end date. I created custom validator

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

And I created ClientSideValidations custom validator. I wasn't sure how I can get another attributes values in it, but I tried to do this in such way:

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;
  }
}

But it doesn't work/ I have error only after reloading page, but not with client side validations. I use client_side_validations (3.2.0.beta.3), client_side_validations-formtastic (2.0.0.beta.3), rails (3.2.3)

Was it helpful?

Solution

The code you supplied above is missing any mention of a declaration (and use) of a validator helper method. In the milestone_dates_validator.rb initializer try adding the following at the end of the file:

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

And in your model call the validator on the attribute/s you are validating:

validates_milestone_dates :milestone_ends_at
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top