rails built in datetime validation

前端 未结 6 557
無奈伤痛
無奈伤痛 2020-11-28 10:07

Does rails do any validation for datetime? I found a plugin http://github.com/adzap/validates_timeliness/tree/master, but it seems like something that should come in out

6条回答
  •  天涯浪人
    2020-11-28 10:33

    Recent versions of Rails will type cast values before validation, so invalid values will be passed as nils to custom validators. I'm doing something like this:

    # app/validators/date_time_validator.rb
    class DateTimeValidator < ActiveModel::EachValidator
      def validate_each(record, attribute, value)
        if record.public_send("#{attribute}_before_type_cast").present? && value.blank?
          record.errors.add(attribute, :invalid)
        end
      end
    end
    
    # app/models/something.rb
    class Something < ActiveRecord::Base
      validates :sold_at, date_time: true
    end
    
    # spec/models/something_spec.rb (using factory_girl and RSpec)
    describe Something do
      subject { build(:something) }
    
      it 'should validate that :sold_at is datetimey' do
        is_expected.not_to allow_value(0, '0', 'lorem').for(:sold_at).with_message(:invalid)
        is_expected.to allow_value(Time.current.iso8601).for(:sold_at)
      end
    end
    

提交回复
热议问题