开发者

How to write a validation for exactly 3 digits in ruby-on-rails?

开发者 https://www.devze.com 2023-04-11 02:36 出处:网络
In my controller I have this : validates_presence_of :order_of_importance, :on => :create, :with =>开发者_JS百科 /^\\d{3}$/

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
0

精彩评论

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

关注公众号