2013-02-15 56 views
1

標題不是必填字段。
我只是想驗證時,它不是零(僅當用戶鍵入的東西)如何在這種情況下設置驗證?

validates_format_of :title, :with => /\A[A-Za-z0-9_]+\z/, :message => "must be half-width English numbers and letters, and_" 

但是,一旦我設置,標題字段成爲必填字段。
我怎樣才能設置它,只有當標題字段不是零時驗證?

回答

2

,我認爲這會工作:

validates_format_of :title, :with => /\A[A-Za-z0-9_]+\z/, :message => "must be half-width English numbers and letters, and_", :if => lambda{ !self.title.nil? } 
+0

非常感謝:)這是完美的答案!我會在8分鐘內檢查答案 – HUSTEN 2013-02-15 04:12:26

+0

很樂意提供幫助:-) – rainkinz 2013-02-15 04:14:55

+0

非常感謝:) – HUSTEN 2013-02-15 04:21:04