4

I have in model Invitation a field and attribute like:

field :recipients, :type => Array

I have an array with 4 emails in my controller like:

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

I want validate in my model that each array's value match with a email regex sth like:

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

How can I validate regex of an array in mongoid?

1 Answer 1

6

How about:

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you @clyfe, This code goes in controller or in Model? its possible add a method with this code before_save callback? Thank you
It goes in the model. Not sure what you mean on second phrase.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.