flyte321
flyte321

Reputation: 420

Rails regex: validates_format_for date format with two different separators

I want to validate European date formats like "10.02.2012" or "10-02-2012" in my model.

Therefore I am using this line:

validates_format_of :matchdate, :with => /\A\d{2}(\.|-)\d{2}(\.|-)\d{4}\Z/i, :message => "Date incorrect"

The regex must be right, but whatever I type in, it always returns "Date incorrect".

I get the input from a form where I use

<%= f.text_field :matchdate, :size => '10' %>

together with the Datepicker UI, that outputs the right format. (I want to use both "." and "-" seperators, cause I collect the date in another scope, where both versions should be allowed.)

The params look correct as well, there it says: "...matchdate"=>"29.09.2012"

What am I doing wrong?

Upvotes: 0

Views: 596

Answers (1)

Laas
Laas

Reputation: 6068

When you initiate new instance of your model from params, Rails casts your date into Date object (example using my own model):

i = Invoice.new due_date: "29.09.2012"
i.due_date                              #=> Sat, 29 Sep 2012 
i.due_date.class                        #=> Date 

But you can't validate Date with a Regex. What you actually need is

validates :matchdate, presence: true

because it will be nil if Rails can't parse it, and maybe add some custom validators if needed.

Upvotes: 1

Related Questions