开发者

Rails 3 validates_format_of not working for a simple regex

开发者 https://www.devze.com 2023-02-03 08:57 出处:网络
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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消