0

I have the following three validations in a model in my rails app:

  validates_presence_of :reset_code, message: 'Please enter your reset code'
  validates_length_of :reset_code, is: 4, message: 'Your reset code should be 4 digits'
  validates_format_of :reset_code, with: /\A[0-9]{4}\z/, message: 'Please enter a valid reset code'

I only want to fire the second and third validations if the first is valid (as there is no point in telling the user the reset code isn't the correct length or format if they haven't entered one at all).

So something along the lines of:

validates_length_of :reset_code, is: 4, message: 'Your reset code should be 4 digits', :if => :reset_code.present?
0

1 Answer 1

1

You should use new the new validation syntax, and provide a simple if: condition:

  validates :reset_code, length: { is: 4 },
    message: 'Your reset code should be 4 digits',
    if: -> { reset_code.present? }

  validates :reset_code, format: { with: /\A[0-9]{4}\z/ },
    message: 'Please enter a valid reset code',
    if: -> { reset_code.present? }
Sign up to request clarification or add additional context in comments.

6 Comments

Can I achieve this with the older syntax?
Ah, it was because I had used :if => rather than if: ->
What if I want the third to only fire if the first and second have passed? So instead of checking if it is present, check the validation itself is valid?
Could I just do: if: -> { validates_length_of.valid? }
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.