legendary_rob
legendary_rob

Reputation: 13012

Rails custom Validations - model layer

I am building a custom validation for one of our models that validates the format of a date. so that the dates should be dd/mm/yyyy currently it works with dd/mm/yyyy and dd-mm-yyyy. but we find that some people are entering ddmmyyyy and then rails eats that up and spits out something else.

So i made a custom validation

class DateFormatValidator < ActiveModel::Validator
  def validate(record)
    record.errors[:transaction_date] << "Date must be in the following format: mm/dd/yyyy" unless /\d{2}\/\d{2}\/\d{4}/.match(record.transaction_date)
  end
end

Then within the model that i want to validate the transaction_date i create a private model like this

def date_is_correct_format
  validates_with DateFormatValidator
end

And then call validate :date_is_correct_format

I have done this before but this time this doesn't seem to be working, and no exceptions are raised at all. I could even within the private method do this.

def date_is_correct_format
  this_is_a_fake_method_that_should_blow_up
  validates_with DateFormatValidator
end

and it runs the validations and passes everything fine. any idea as to what i am missing? i have been readinig the Ruby on Rails API but i cant see anything?

Upvotes: 0

Views: 223

Answers (1)

zuozuo
zuozuo

Reputation: 386

I have tried the code you posted above, and it worked well.

  class User < ActiveRecord::Base
    validate :date_is_correct_format

    def date_is_correct_format
      validates_with DateFormatValidator
    end
  end

  class DateFormatValidator < ActiveModel::Validator
    def validate(record)
      record.errors[:transaction_date] << "Date must be in the following format: mm/dd/yyyy" unless /\d{2}\/\d{2}\/\d{4}/.match(record.transaction_date)
    end
  end

Then i try in console, the output is:

  [1] pry(main)> User.create!(:transaction_date=>'fdsf')
     (0.1ms)  begin transaction
     (0.1ms)  rollback transaction
  ActiveRecord::RecordInvalid: Validation failed: Transaction date Date must be in the following       format: mm/dd/yyyy
  from /Users/zuozuo/.rvm/gems/ruby-2.0.0-p247@rails4/gems/activerecord-    4.0.0/lib/active_record/validations.rb:57:in `save!'

So what version of Rails do you use ?

or you can try:

  class User < ActiveRecord::Base
    validates_with ::DateFormatValidator
  end

this implement also works.

Upvotes: 1

Related Questions