在我的 user.rb
模型中,我有一个 email_confirm
字段,以便用户插入两次并验证电子邮件而不会出现拼写错误
attr_accessor :email_confirmation
validates :email, confirmation: true, on: :create
validates :email_confirmation, presence: true, allow_nil: true
但实际情况是,如果我插入一封大写字母的电子邮件,我会收到验证错误 “不匹配”
。如何在不区分大小写的情况下确认电子邮件?
我正在使用设计
最佳答案
对于电子邮件验证,使用正则表达式匹配器:
validates_format_of :email, with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
正则表达式末尾的 i
标志设置不区分大小写。此验证还处理存在性,因为 nil 或空白字符串将无法通过上述验证。
我推荐使用 Rubular 来测试正则表达式:http://rubular.com/
编辑
您可以在 before_validation
block 中预处理属性:
before_validation :downcase_email
def downcase_email
email_confirmation.try(:downcase!)
email.try(:downcase!)
end
try
是为了防止在 email 为 nil 时调用 downcase!
。
关于ruby-on-rails - Rails 验证确认 true 不区分大小写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36847989/