2012-03-02 68 views
4

我在模型邀請一個字段和屬性等:validate數組mongoid和Ruby on Rails

field :recipients, :type => Array 

我有4個電子郵件的陣列在我的控制器,如:

@invitation.recipients = ['', '', '', ''] 

我希望在我的模型中驗證每個數組的值與電子郵件正則表達式匹配......例如:

validates_format_of :recipients, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/u, :message => "is not a valid email address" 

如何驗證mongoid中數組的正則表達式?

回答

6

如何:

RE = /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/u 
validate :recipients_format 
def recipients_format 
    unless recipients.all? { |r| r =~ RE } 
    errors[:recipients] = "are not all valid email addresses" 
    end 
end 
+0

謝謝@clyfe,該代碼放在控制器或模型?它可能添加一個方法與此代碼before_save回調?謝謝 – hyperrjas 2012-03-02 09:49:00

+0

它在模型中。不確定你在第二個短語中的含義。 – clyfe 2012-03-02 10:14:33

+0

非常感謝。也就是說,它工作得很好! – hyperrjas 2012-03-02 10:23:04