How to write a validation for exactly 3 digits in ruby-on-rails?
In my controller I have this :
validates_presence_of :order_of_importance, :on => :create, :with =>开发者_JS百科 /^\d{3}$/
But this would still validate ( i think ), if they typed :
4231
But I want to make sure they only type in 3 digit characters.
Any ideas?
/^\d{3}$/
should do it. It makes sure that the digits start and end at the ends of the string to match.
Also, you don't need the i
at the end, since digits aren't cased.
You can try
validates_length_of :order_of_importance, :maximum => 3
A perhaps "more Railsy" way would be:
validates_length_of :order_of_importance, :on => :create, :is => 3
validates_numericality_of :order_of_importance, :on => :create
精彩评论