Lalala Yang
Lalala Yang

Reputation: 9

Rails 5 break validating chain when a validation failed

In my user model I have a validation rule like:

validates :email, presence: true, my_email_format: true, uniqueness: true

I want to break the chain when any validation is failed, such as when the email format is wrong (my_email_format failed), the uniqueness validation will not run.

Upvotes: 0

Views: 1037

Answers (2)

Yuliyan
Yuliyan

Reputation: 203

I would suggest you to create before_validation hook. Throw :abort message when you want to break the validation chain.

For example:

before_validation :validate_email, on: :create

...

def validate_email
  if (email_is_invalid)
    errors.add(:base, error_message)
    throw(:abort)
  end
end

Upvotes: 0

SteveTurczyn
SteveTurczyn

Reputation: 36860

I'm not sure why you want that but if you want to, you can split the validates into multiple lines

validates :email, presence: true
validates :email, my_email_format: true, if: ->{errors[:email].blank?}
validates :email, uniqueness: true, if: ->{errors[:email].blank?}

Upvotes: 1

Related Questions