Same custom validation for several fields in Rails

后端 未结 2 361
无人共我
无人共我 2020-12-17 03:22

I have four date_time fields in my model in Rails app. I want to apply the same validation method to them, so that only a valid date time could be accepted. Validation metho

相关标签:
2条回答
  • 2020-12-17 04:11
    def self.validate_is_valid_datetime(field)
      validate do |model|
        if model.send("#{field}?") && ((DateTime.parse(model.send(field)) rescue ArgumentError) == ArgumentError)
          model.errors.add(field, 'must be a valid datetime')
        end
      end
    end
    
    validate_is_valid_datetime :datetime_field
    
    0 讨论(0)
  • 2020-12-17 04:12

    Best solution is to create your own validator:

    class MyModel < ActiveRecord::Base
      include ActiveModel::Validations
    
      class DateValidator < ActiveModel::EachValidator
        def validate_each(record, attribute, value)
          record.errors[attribute] << "must be a valid datetime" unless (DateTime.parse(value) rescue nil)
        end
      end
      validates :datetime_field, :presence => true, :date => true
      validates :another_datetime_field, :presence => true, :date => true
      validates :third_datetime_field, :presence => true, :date => true
    end
    

    UPD

    you can share same validations this way:

      validates :datetime_field, :another_datetime_field, :third_datetime_field, :presence => true, :date => true
    
    0 讨论(0)
提交回复
热议问题