我允许电子邮件有时是可选的,具体取决于是否有phone
字段。如果存在 - 不验证存在,如果没有 - 验证它。这是代码:
# model.rb
validates :email, length: {maximum: 255},
uniqueness: {case_sensitive: false},
email: true
validates_presence_of :email, unless: Proc.new {|user| user.phone? }
问题在于,如果用户提交空email
字段,则Email has already been taken
和Email is not an email
会出错。
我还有email_validator.rb
:
class EmailValidator < ActiveModel::EachValidator
def validate_each(record, attr_name, value)
unless value =~ MY_EMAIL_REGEX
record.errors.add(attr_name, 'is not an email')
end
end
end
我想:
答案 0 :(得分:1)
您在Proc
的一次验证中使用了email
,但在其他验证中没有使用{},
validates :email, length: {maximum: 255},
uniqueness: {case_sensitive: false},
allow_blank: true, # This option will let validation pass if the attribute's value is blank?, like nil or an empty string
email: true, unless: Proc.new {|user| user.phone? }
validates_presence_of :email, unless: Proc.new {|user| user.phone? }
您可以合并这两个验证:
validates :email, length: {maximum: 255},
uniqueness: {case_sensitive: false},
presence: true,
allow_blank: true, # This option will let validation pass if the attribute's value is blank?, like nil or an empty string
email: true, unless: Proc.new {|user| user.phone? }