本篇詳細介紹 Rails 內建驗證機制,逐步為 Product 模型加入必填欄位、數值格式、唯一性、圖片網址格式與自訂驗證規則。
class Product < ActiveRecord::Base validates_presence_of :title, :description, :image_url end
未填寫時會顯示錯誤訊息(如下圖)。

validates_numericality_of :price
輸入非數字時提示錯誤(如下圖)。

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
說明:
validates_presence_of:必填驗證validates_numericality_of:數值驗證validates_uniqueness_of:唯一性驗證validates_format_of:正則表達式驗證圖片網址格式validate 方法:確保價格為正數這些驗證將在表單送出時自動執行,錯誤訊息會回傳給視圖顯示。