rails有一個”簡潔、完美的驗證機制,無比強大的表達式和驗證框架“。在《Agile Web Development with Rails 4th》一書的7.1節向我們展示了如何驗證Product:
class Product < ActiveRecord::Base
validates :title, :description, :image_url, :presence => true
validates :price, :numericality => {:greater_than_or_equal_to => 0.01}
validates :title, :uniqueness => true
validates :image_url, :format => {
:with => %r{\.(gif|jpg|png)$}i,
:message => 'must be a URL for GIF, JPG or PNG image.'
}
end
還是需要解釋一下:
validates :title, :description, :image_url, :presence => true :這三個字段不能為空。rails默認是允許為空。而且由於model與migration是分開定義的,你可以在migration中定義字段不能為空而model中可以為空,或者反之。
validates :price, :numericality => {:greater_than_or_equal_to => 0.01}:price字段應該是有效的數字並且不小於0.01
validates :image_url, :format => {…}: image_url 必須以三種擴展名結尾,這里沒有驗證是否為有效的url
更加可怕的是,這個驗證語法是rails3.0開始支持的,而在此之前的版本要寫成這樣:
class Product < ActiveRecord::Base
validates_presence_of :title, :description, :image_url
validates_numericality_of :price
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
再讓我們看看”簡潔“的rails驗證還有哪些功能(舊版語法):
validates_acceptance_of: 驗證指定checkbox應該選中。這個怎么看都應該是form中的驗證而與model無關
validates_associated:驗證關聯關系
validates_confirmation_of:驗證xxx與xxx_confirmation的值應該相同。 這個怎么看也應該是form中的驗證而與model無關
validates_length_of:檢查長度
validates_each 使用block檢驗一個或一個以上參數
validates_exclusion_of 確定被檢對象不包括指定數據
validates_inclusion_of 確認對象包括在指定范圍
validates_uniqueness_of檢驗對象是否不重復
也許還有more and more, and more, and more…
回到Django。Django的驗證有3層機制:
1. Field類型驗證。除了能夠對應到數據庫字段類型的Field類型外,還有 EmailField,FileField,FilePathField,ImageField,IPAddressField,PhoneNumberField、 URLField、XMLField等,
2. Field選項驗證。如,null=true,blank=true, choices,editable,unique,unique_for_date,unique_for_month,unique_for_year 等等。有些Field還有自己獨有的選項,也可以用來約束數據。
3. 表單(Form)驗證。還可以在Form中定義驗證方法。可以定義整個Form的驗證方法 clean,或者針對某個表單項的驗證方法:clean_xxx。
前面建立的Product模型中,已經默認加入了不能為空、要求符合數字等驗證,所以還需要進行如下驗證:
1.驗證price>0:需要在Form中驗證;
2. 驗證title唯一:在Model中驗證;
3. 驗證image_url的擴展名:在Form中驗證,還可以順便在Model中將其改為URLField類型。
