Skip to content

Instantly share code, notes, and snippets.

@chrisyour
Created March 8, 2011 19:37
Show Gist options
  • Save chrisyour/860865 to your computer and use it in GitHub Desktop.
Save chrisyour/860865 to your computer and use it in GitHub Desktop.
Simple date validator for Rails 3.
# Validator:
# /app/validators/date_validator.rb
class DateValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
unless value.to_s =~ /^\d{4}-\d{2}-\d{2}$/i
record.errors[attribute] << (options[:message] || "is an invalid date")
end
end
end
# Use:
# /app/models/post.rb
class Post < ActiveRecord::Base
validates :published_on, :date => true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment