gabriele renzi
3/29/2006 10:37:00 PM
Dara Sanderson ha scritto:
> Hello,
>
> I hope someone can help me or at least confirm that I'm not going
> insane.
>
> I have a model in which I'm trying to validate information before it
> saves.
> One particular field is for and expiration date. The code in my model
> to do the validation looks like this:
>
> validates_format_of :expiration,
> :with => %r{^[\d]{4,4}$},
> :message => "must be formatted (mmyy)"
>
>
> The problem is if someone enter a date that starts with a zero like
> "0309" The validation somehow just doesn't "see" the leading zero and
> keeps returning an error as though the user isn't submitting it
> properly. I did verify that the controller is definetly sending all
> four digits in the post.
I think I'd write the Regexp as:
%r{^\d{4}$}
Anyway, you one seem to work as expected on my box in irb:
irb(main):001:0> x=/^[\d]{4,4}$/
=> /^[\d]{4,4}$/
irb(main):002:0> x2=%r|^[\d]{4,4}$|
=> /^[\d]{4,4}$/
irb(main):003:0> x.match "0102"
=> #<MatchData:0x2c0b300>
irb(main):004:0> x2.match "0102"
=> #<MatchData:0x2c08fa8>
and in rails:
$cat app\models\foo.rb
class Foo < ActiveRecord::Base
validates_format_of :bar, :with=>%r{^\d{4}$}
end
>> f=Foo.new
=> #<Foo:0x39658e8 @new_record=true, @attributes={"bar"=>""}>
>> f.bar ="0123"
=> "0123"
>> f.save
=> true
>> f.bar ="012"
=> "012"
>> f.save
=> false
what version of ruby are you running?
Maybe it could have been some damn pesky problem like not having
reloaded the model (this happened to me many times :) ?