rails built in datetime validation

前端 未结 6 549
無奈伤痛
無奈伤痛 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:28

    You can create a custom datetime validator by yourself

    1) create a folder called validators in inside app directory

    2) create a file datetime_validator.rb. with the following content inside app/validators directory

     class DatetimeValidator < ActiveModel::EachValidator
      def validate_each(record, attribute, value)
        if ((DateTime.parse(value) rescue ArgumentError) == ArgumentError)  
          record.errors[attribute] << (options[:message] || "must be a valid datetime")
        end
      end
    end
    

    3) Apply this validation on model

    class YourModel < ActiveRecord::Base
      validates :happend_at, datetime: true
    end
    

    4) Add the below line in application.rb

    config.autoload_paths += %W["#{config.root}/app/validators/"]
    

    5) Restart your rails application

    Note: The above method tested in rails 4

提交回复
热议问题