Rails中验证
1. validates_presence_of
validates_presence_of()方法是一个标准的Rails验证器,它会检查指定字段存在、并且值不为空。
用法,例如:(C:\Users\Tony\Desktop\rails\deopt\app\models\product.rb)
class Product < ActiveRecord::Base validates_presence_of :title, :description, :image_urlend
class Product < ActiveRecord::Base validates_presence_of :title, :description, :image_url validates_numericality_of :price validate :price_must_be_at_least_a_cent protected def price_must_be_at_least_a_cent errors.add(:price, 'should be at least 0.01' ) if price.nil? || price < 0.01 endend
validates_uniqueness_of :title
validates_format_of :image_url, :with => %r{\.(gif|jpg|png)$}i, :message => 'must be a URL for GIF, JPG or PNG image.'