Last active
December 20, 2015 00:09
-
-
Save glaucocustodio/6039161 to your computer and use it in GitHub Desktop.
Rails 4 and Ruby 2 date format validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Model | |
# Working in Rails 3 with Ruby 1.9.3 - always returning false in Rails 4 with Ruby 2 | |
with_options :if => :condition? do |co| | |
co.validates :date_birth, :format => {:with => /[0-3]{1}[0-9]{1}\/[0-1]{1}[0-9]{1}\/[1-2]{1}[0-9]{3}/, :message => "invalid"} | |
# I also tried below and many others regex | |
#co.validates :date_birth, :format => {:with => /[1-2]{1}[0-9]{3}\-[0-1]{1}[0-9]{1}\-[0-3]{1}[0-9]{1}/, :message => "invalid"} | |
end | |
# Workaround to work in Rails 4 with Ruby 2 | |
with_options :if => :condition? do |co| | |
co.validate :valid_date_birth | |
end | |
private | |
def valid_date_birth | |
if self.date_birth.blank? || !(/[1-2]{1}[0-9]{3}\-[0-1]{1}[0-9]{1}\-[0-3]{1}[0-9]{1}/.match(self.date_birth.to_s)) | |
errors[:date_birth] = 'invalid' | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment