Answer the question
In order to leave comments, you need to log in
How to validate the time span in a rail model?
There is a simple rails application, there is a user model User, the user has a date_of_birth field
How to validate this field in the model to check that date_of_birth is in the range from 01/01/1900 to today, inclusive, despite the fact that this field may not be at all, but if there is, then it fits this range.
Answer the question
In order to leave comments, you need to log in
class User < ApplicationRecord
validates_with UserBirthZalupaValidator
end
class UserBirthZalupaValidator < ActiveModel::Validator
def validate(record)
begin
birth = Date.parse(record.birth_date.to_s)
record.errors.add(:base, "zlpa") unless birth.between?(start_date, end_date)
rescue StandardError => e
Rails.logger.error("Full zlpa: #{e.inspect}")
end
end
def start_date
Date.new(1900,1,1)
end
def end_date
Time.zone.today
end
end
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question