How do I validate members of an array field?

后端 未结 5 729
一整个雨季
一整个雨季 2020-12-14 10:30

I have this model:

class Campaign

  include Mongoid::Document
  include Mongoid::Timestamps

  field :name, :type => String
  field :subdomain, :type =&g         


        
5条回答
  •  独厮守ぢ
    2020-12-14 11:15

    Found myself trying to solve this problem just now. I've modified Tim O's answer slightly to come up with the following, which provides cleaner output and more information to the errors object that you can then display to the user in the view.

    validate :validate_emails
    
    def validate_emails
      emails.each do |email|
        unless email.match(/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i)
          errors.add(:emails, "#{email} is not a valid email address.")
        end
      end
    end
    

提交回复
热议问题