Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date Validation In Rails 3

I've got a Rails 3 app (using Mongodb and Mongoid if that makes a difference), and in one of my models I have a field defined as a Date type.

class Participant
  include Mongoid::Document

  field :birth_date, :type => Date
end

My controller is using the find_or_initialize_by feature of mongo:

class ParticipantController

  def create
    @participant = Participant.find_or_initialize_by(params[:participant])
    if @participant.save
      redirect_to participants_path
    else
      render :new
    end
  end
end

All this boils down to: how do I do date validation in ActiveModel with Mongoid and Rails 3?

I want to make sure an input of "blah" as in a textbox does not throw an exception when assigned to the .birth_date field of my model. It should provides a nice validation error message without using the controller to do the validation.

Here's the basic requirements:

  • The view must be a single textbox. Nothing else. This is a user requirement that we cannot change

  • The validation should be done in the model, not in the controller or the
    view (javascript or whatever)

  • No regex format validations (they don't work right / support locale's etc)

The problem is that the value from the textbox is assigned to the .birth_date before validates_format_of and validates_presence_of are run. so...

how do I intercept the assignment of the value, so that I can validate it before it gets assigned? is it possible to do that in the model, using ActiveModel? or does this require me putting code in the controller to do this?

like image 800
Derick Bailey Avatar asked Nov 19 '10 02:11

Derick Bailey


2 Answers

This small block of code may do the trick

retVal = "it is a date"
begin
  y = Date.parse("rodman was here")
rescue
  retVal = "nope not a date"
end

puts retVal
like image 159
Rod Paddock Avatar answered Sep 22 '22 23:09

Rod Paddock


The validates_timeliness gem is pretty sweet. You can just do something like this:

class Participant < ActiveRecord::Base
  validates_date :birth_date
end
like image 43
Jason Swett Avatar answered Sep 23 '22 23:09

Jason Swett