如何在我的情况下跳过格式验证?

时间:2014-05-22 02:49:08

标签: ruby-on-rails ruby ruby-on-rails-3 validation ruby-on-rails-3.2

我有一个具有属性的模型用户"来宾" (布尔) 如果user.guest == true或user.guest == nil,我想跳过电子邮件的格式验证,

尝试

VALID_EMAIL_REGEX = /^(\S+)@([a-z0-9-]+)(\.)([a-z]{2,4})(\.?)([a-z]{0,4})+$/i
validates :email, format: { :with => VALID_EMAIL_REGEX } unless :guest?

但现在即使用户有guest == false或guest == nil验证仍在跳过

可能出现什么问题?

另一种常见的验证效果很好:

validates :email, presence: true,
                    uniqueness: { case_sensitive: false } unless :guest?

1 个答案:

答案 0 :(得分:1)

试试这段代码: -

VALID_EMAIL_REGEX = /^(\S+)@([a-z0-9-]+)(\.)([a-z]{2,4})(\.?)([a-z]{0,4})+$/i
validates :email, presence: true, format: {with: VALID_EMAIL_REGEX},
uniqueness: {case_sensitive: false},  unless: :guest?