how to skip format validation in my case?

拜拜、爱过 提交于 2019-12-08 13:24:58

问题


I have a model User with an attribute "guest" (BOOLEAN) I want to skip format validation on email if user.guest == true or user.guest == nil,

tried

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?

but now even when user have guest == false or guest == nil validation is still skipping

What could be wrong?

another common validation works good:

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

回答1:


Try this code:-

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?


来源:https://stackoverflow.com/questions/23797041/how-to-skip-format-validation-in-my-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!