Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Validate with arguments

I am using Rails 3.0.3 where I have quite an extensive validation process.

I want to make a validation where I check if a certain variable is a proper date

Basically this is what I want to do is:

def validate_date(this_date)?

    begin
       Date.parse(this_date)
    rescue
      proper_date = false
    else
          proper_date = true
    end
end

and call this method in my model using:

attr_accessor :given_date    
validate_date(given_date)

but also at another place in my validation file using for example:

attr_accessor :another_date
validate_date(another_date)

or something similar...

What do I need to do to make this work?

like image 637
Christoffer Avatar asked Mar 21 '26 14:03

Christoffer


1 Answers

you want to add errors instead of returning false, so instead you want to use:

errors.add(:date, "is invalid")
like image 107
Niclas Kirschmeier Avatar answered Mar 24 '26 07:03

Niclas Kirschmeier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!