Rails 版本 6.0.1
class DateValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
rawValue = record.send(attribute.to_s + '_before_type_cast')
if (Date.parse(rawValue) rescue ArgumentError) == ArgumentError
record.errors.add attribute, :data_error
end
end
end
class User < ApplicationRecord
validates :date_of_birth, date: true
end
irb(main):001:0> user = User.new date_of_birth: '2020-02-02'
irb(main):002:0> user.valid?
=> true
irb(main):003:0> user.save
(0.2ms) BEGIN
User Create (0.3ms) INSERT INTO "users" ("date_of_birth") VALUES ($1, $2, $3) RETURNING "id" [["date_of_birth", "2020-02-02"], ["created_at", "2020-02-24 05:12:27.657736"], ["updated_at", "2020-02-24 05:12:27.657736"]]
(0.9ms) COMMIT
=> true
irb(main):004:0> user.valid?
=> false
irb(main):005:0> user.errors
=> #<ActiveModel::Errors:0x00005606b0872eb0 @base=#<User id: 1, date_of_birth: "2020-02-02", created_at: "2020-02-24 05:12:27", updated_at: "2020-02-24 05:12:27">, @messages={:date_of_birth=>["日期有误"]}, @details={:date_of_birth=>[{:error=>:data_error}]}>
谁知道到底哪里出了问题?