Ruby-on-rails rails 内置日期时间验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1370926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:42:04  来源:igfitidea点击:

rails built in datetime validation

ruby-on-railsvalidation

提问by Daniel

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 of the box.

rails 是否对日期时间进行任何验证?我找到了一个插件 http://github.com/adzap/validates_timeliness/tree/master,但它似乎应该是开箱即用的。

回答by Gabe Hollombe

There's no built-in ActiveRecord validator for DateTimes, but you can easily add this sort of capability to an ActiveRecord model, without using a plugin, with something like this:

DateTimes 没有内置的 ActiveRecord 验证器,但是您可以轻松地将这种功能添加到 ActiveRecord 模型中,而无需使用插件,如下所示:

class Thing < ActiveRecord::Base
  validate :happened_at_is_valid_datetime

  def happened_at_is_valid_datetime
    errors.add(:happened_at, 'must be a valid datetime') if ((DateTime.parse(happened_at) rescue ArgumentError) == ArgumentError)
  end
end

回答by Sauce McBoss

Gabe's answer didn't work for me, so here's what I did to validate my dates:

Gabe 的回答对我不起作用,所以这是我为验证日期所做的工作:

class MyModel < ActiveRecord::Base
  validate :mydate_is_date?

  private

  def mydate_is_date?
    if !mydate.is_a?(Date)
      errors.add(:mydate, 'must be a valid date') 
    end
  end
end

I was just looking to validate that the date is in fact a date, and not a string, character, int, float, etc...

我只是想验证日期实际上是日期,而不是字符串、字符、整数、浮点数等...

More complex date validation can be found here: https://github.com/codegram/date_validator

更复杂的日期验证可以在这里找到:https: //github.com/codegram/date_validator

回答by Halil ?zgür

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

最新版本的 Rails 将在验证之前输入类型转换值,因此无效值将作为nils传递给自定义验证器。我正在做这样的事情:

# 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

回答by Tsutomu

I recommend a gem date_validator. See https://rubygems.org/gems/date_validator. It is well maintained and its API is simple and compact.

我推荐一颗宝石date_validator。请参阅https://rubygems.org/gems/date_validator。它维护良好,其 API 简单紧凑。

回答by Developer

You can create a custom datetime validator by yourself

您可以自己创建自定义日期时间验证器

1) create a folder called validators in inside app directory

1)在app目录中创建一个名为validators的文件夹

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

2) 创建文件 datetime_validator.rb。在 app/validators 目录中包含以下内容

 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

3)将此验证应用于模型

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

4) Add the below line in application.rb

4)在application.rb中添加以下行

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

5) Restart your rails application

5) 重启你的 rails 应用程序

Note: The above method tested in rails 4

注意:以上方法在rails 4中测试

回答by Ariejan

It's quite necessary to validate dates. With the default Rails form helpers you could select dates like September 31st.

非常有必要验证日期。使用默认的 Rails 表单助手,您可以选择像 9 月 31 日这样的日期。