How to validate the date such that it is after today in Rails?

后端 未结 5 566
伪装坚强ぢ
伪装坚强ぢ 2021-02-03 19:07

I have an Active Record model that contains attributes: expiry_date. How do I go about validating it such that it is after today(present date at that time)? I am totally new to

5条回答
  •  孤独总比滥情好
    2021-02-03 19:11

    Here's the code to set up a custom validator:

    #app/validators/not_in_past_validator.rb
    class NotInPastValidator < ActiveModel::EachValidator
      def validate_each(record, attribute, value)
        if value.blank?
          record.errors.add attribute, (options[:message] || "can't be blank")
        elsif value <= Time.zone.today
          record.errors.add attribute,
                            (options[:message] || "can't be in the past")
        end
      end
    end
    

    And in your model:

    validates :signed_date, not_in_past: true
    

提交回复
热议问题