我有一个具有属性的模型用户"来宾" (布尔) 如果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?
答案 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?