Having troub开发者_如何转开发le getting a simple validation to work in Rails 3, even though the regex works fine. Even with a valid format, the validation fails.
Model:
validates_format_of :start,
with: /\A[0-9]{2}\/[0-9]{2}\/[0-9]{4}\z/,
message: "Invalid date format"
Assertion:
Event.new(start: "12/10/2010").valid?.should eq(true)
That assertion is failing because valid?
returns false
.
What am I missing?
The regex fails because start
is a Date
type, and when the object is instantiated with a string, ActiveRecord automagically converts it to a Date
. By the time the validator gets ahold of it, it's no longer a string, so there's no match.
精彩评论