Sha256: ad79eb0affbbdcc525f968f40e5f938fed4c40606e73259d80e793a943f1b939

Contents?: true

Size: 740 Bytes

Versions: 3

Compression:

Stored size: 740 Bytes

Contents

module NewspaperWorks
  # validates that a properly formatted date has been entered
  class PublicationDateValidator < ActiveModel::Validator
    DATE_REGEX = /\A\d{4}-((0[1-9])|(1[0-2]))-((0[1-9])|([1-2][0-9])|(3[0-1]))\z/
    def validate(record)
      error_msg = "Incorrect Date. Date input should be formatted yyyy-mm-dd and be a valid date."
      return unless record.publication_date.present?
      unless DATE_REGEX.match(record.publication_date)
        record.errors[:publication_date] << error_msg
        return
      end
      date_split = record.publication_date.split("-").map(&:to_i)
      record.errors[:publication_date] << error_msg unless Date.valid_date?(date_split[0], date_split[1], date_split[2])
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
newspaper_works-1.0.1 app/validators/newspaper_works/publication_date_validator.rb
newspaper_works-1.0.0 app/validators/newspaper_works/publication_date_validator.rb
newspaper_works-0.1.0 app/validators/newspaper_works/publication_date_validator.rb