问题
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