1.打开depotappmodels目录下的product.rb文件,向其中添加代码,如下:
class Product
< ActiveRecord::Base
validates_presence_of
:title, :description, :image_url
end
2.再次打开http://127.0.0.1:3000/Admin/New,留下title,description,image_url不输入,直接点击Create按钮,会显示错误页面。
3.上面添加的是必须录入项的验证,下面添加Price项必须为数字的验证。
向Product.rb中添加代码:
validates_numericality_of :price
添加代码后,Product.rb的Ruby on Rails验证输入代码如下:
class Product
< ActiveRecord::Base
validates_presence_of
:title, :description, :image_url
validates_numericality_of :price
end
4.再次打开Admin/New页面,给Price项输入字符,点击Create按钮,会看到错误提示,如下图:
5.下面,我们依次添加验证项,最后Product.rb的内容为:
class Product < ActiveRecord::Base
validates_presence_of :title,
:description, :image_url
validates_numericality_of :price
validates_uniqueness_of :title
validates_format_of :image_url,
:with => %r{^http:.+.(gif|jpg|png)$}i,
:message => "must be a URL for a
GIF, JPG, or PNG image"
protected
def validate
errors.add(:price, "should be
positive") unless price.nil? || price > 0.0
end
end
下面依次解释Ruby on Rails验证输入中的一些方法:
validates_presence_of :title, :description, :image_url :必输入项验证。
validates_numericality_of :price:数值验证
validates_uniqueness_of :title:唯一验证,如果title有重复的,表示error。
validates_format_of :image_url,
:with => %r{^http:.+.(gif|jpg|png)$}i,
:message => "must be a URL for a GIF, JPG, or PNG image"
对Image_url项验证是否为图片,是否是一个url地址。
protected
def validate
errors.add(:price, "should be
positive") unless price.nil?
|| price > 0.0
end
给price再添加一个验证,看是否为整数。
OK,今天的Ruby on Rails验证输入就写到这里。
验证输入技术讲解
最新推荐文章于 2022-09-02 13:32:36 发布