Catfish
Catfish

Reputation: 19324

Trying to validate a date

I have a form where i'm trying to validate that a field called "birthday" is not blank, and that the date is a valid date format that the Chronic gem can parse. I always get the error message "Birthday is invalid". I've been trying a simple format "10/10/2010".

How can i validate that the birthday field is of a format that chronic can parse?

User.rb model

class User < ActiveRecord::Base

  validates :birthday, :presence => true
  validate :birthday_is_date
  validate :position, :presence => true

  # validate the birthday format
  def birthday_is_date
    errors.add(:birthday ,Chronic.parse(birthday)) # testing to see the value of :birthday
    errors.add(:birthday, "is invalid test message") if ((Chronic.parse(:birthday) rescue ArgumentError) == ArgumentError)
  end
end

contacts_controller.rb

# POST /contacts/1/edit
    # actually updates the users data
    def update_user
        @userProfile = User.find(params[:id])

        respond_to do |format|
            if @userProfile.update_attributes(params[:user])
                format.html {
                    flash[:success] = "Information updated successfully"
                    redirect_to(profile_path)
                }
            else 
                format.html {
                    flash[:error] = resource.errors.full_messages

                    render :edit
                }
            end
        end
    end

Upvotes: 1

Views: 4330

Answers (3)

jhoanna
jhoanna

Reputation: 1857

From chronic.rubyforge.org:

Chronic uses Ruby’s built in Time class for all time storage and computation. Because of this, only times that the Time class can handle will be properly parsed. Parsing for times outside of this range will simply return nil. Support for a wider range of times is planned for a future release.

Time zones other than the local one are not currently supported. Support for other time zones is planned for a future release.

From Date validation in Ruby using the Date object:

A simple validate function

One way to test for a valid date is to try to create a Date object. If the object is created, the date is valid, and if not, the date is invalid. Here is a function that accepts year, month, and day, then returns true if the date is valid and false if the date is invalid.

def test_date(yyyy, mm, dd)
   begin
     @mydate = Date.new(yyyy, mm, dd)
     return true
   rescue ArgumentError
     return false
   end
 end

From the accepted answer of How do I validate a date in rails?:

If you're looking for a plugin solution, I'd checkout the validates_timeliness plugin. It works like this (from the github page):

class Person < ActiveRecord::Base
  validates_date :date_of_birth, :on_or_before => lambda { Date.current }
  # or
  validates :date_of_birth, :timeliness => {:on_or_before => lambda { Date.current }, :type => :date}
end 

The list of validation methods available are as follows:

validates_date - validate value as date
validates_time - validate value as time only i.e. '12:20pm'
validates_datetime - validate value as a full date and time
validates - use the :timeliness key and set the type in the hash.

Upvotes: 1

Dipak Panchal
Dipak Panchal

Reputation: 6036

try this

install validates_date_time gem

you can pass validation for date, for example

class Person < ActiveRecord::Base
    validates_date     :date_of_birth
    validates_time     :time_of_birth
    validates_date_time :date_and_time_of_birth
  end
  

Use :allow_nil to allow the value to be blank.

  class Person < ActiveRecord::Base
    validates_date :date_of_birth, :allow_nil => true
  end

Source : https://github.com/smtlaissezfaire/validates_date_time

Upvotes: 1

Jean-Louis Giordano
Jean-Louis Giordano

Reputation: 1967

Your birthday_is_date validation always adds an error on the first line. It should be written as follows:

def birthday_is_date
  errors.add(:birthday, "is invalid") unless Chronic.parse(birthday)
end

Upvotes: 2

Related Questions