如何验证模型中的多个电子邮件地址? [英] How can I validate multiple email addresses in a model?
问题描述
例如:逗号分隔在单个文本字段中:mail1@domain.com, mail2@someotherdomain, ...
e.g.: comma seperated in a single textfield: mail1@domain.com, mail2@someotherdomain, ...
推荐答案
您可以使用 TMail::Address 模块来验证电子邮件为 此处显示.可以使用 validate
方法添加自定义验证.
You can use the TMail::Address module to validate an email as shown here. Custom validations can be added with the validate
method.
validate :check_email_addresses
def check_email_addresses
email_addresses.split(/,\s*/).each do |email|
TMail::Address.parse(email)
end
rescue TMail::SyntaxError
errors.add(:email_addresses, "are not valid")
end
<小时>
更新: TMail::Address 模块似乎对有效电子邮件地址的定义过于宽松(请参阅下面的评论),因此您可以使用正则表达式.
Update: The TMail::Address module seems to be too lax on what is considered a valid email address (see comments below) so instead you can use a regular expression.
validate :check_email_addresses
def check_email_addresses
email_addresses.split(/,\s*/).each do |email|
unless email =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
errors.add(:email_addresses, "are invalid due to #{email}")
end
end
end
有多种用于验证电子邮件地址的正则表达式解决方案.请参阅此页面了解详情.
There are a variety of regular expression solutions for validating an email address. See this page for details.
这篇关于如何验证模型中的多个电子邮件地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!