Skip to content

Instantly share code, notes, and snippets.

@glaucocustodio
Last active December 20, 2015 00:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glaucocustodio/6039161 to your computer and use it in GitHub Desktop.
Save glaucocustodio/6039161 to your computer and use it in GitHub Desktop.
Rails 4 and Ruby 2 date format validation
# 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