2010-12-07 77 views
0

我知道ActiveRecord提供了一些宏,如validates_uniqueness_ofvalidates_size_of 爲用戶輸入做了一些驗證。但我想知道是否有可能提供 一些回調驗證方法作爲模型級驗證方法。例如, 我想檢查輸入字符串只有字母從'a'到'h',有趣嗎?但它不時發生。如何在rails的模型中添加客戶驗證器

回答

1

您可以創建自定義函數具有:

validate :custom_function 

def custom_function 
    ... 
end 

您還可以使用正則表達式來驗證字符串。對於你的例子,我會用:

validates_format_of :attribute, :with => /^[a-h]+$/ 
1

rails guides有一個如何創建自己的自定義驗證器的很好的例子。如果您在使用Rails 3,你可以做這樣的:

class Foo < ActiveRecord::Base 
    validate :from_a_to_h 

    # Use the name of your attribute in place of :input and input. 
    def from_a_to_h 
    errors.add(:input, "must contain only letters from a to h") if input =~ /[i-Z]+/ 
    end 
end