Rails匹配validates_format_of数字1-9

时间:2012-06-27 12:17:53

标签: ruby-on-rails ruby

您好我想验证表单输入,所以它只需要数字1-9作为输入,如何实现

我在我的模型中有这个,但似乎无法获得匹配的正确

validates_format_of:myfield,:with => ??????,:on => :创建

2 个答案:

答案 0 :(得分:3)

请看一下:http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_inclusion_of

 validates :myfield, :inclusion => { :in => 1..9 }

 validates_inclusion_of :myfield, :in => 1..9

编辑 - 我认为myfieldinteger,但如果您将其定义为string,则需要添加validates_numericality_of

validates_numericality_of :myfield, :only_integer => true
validates_inclusion_of :myfield, :in => 1..9

答案 1 :(得分:1)

validates_format_of :myfield, :with => /([^a-zA-Z][1-9]?)/, :on => :create

如果使用2.3.x

,应该没问题

请注意,它在2.3.8之后删除