0
0
Ruby on Railsframework~5 mins

Conditional validations in Ruby on Rails

Choose your learning style9 modes available
Introduction

Conditional validations let you check data only when certain rules apply. This helps keep your app flexible and accurate.

You want to validate a field only if another field has a specific value.
You need to check a user's input only when they choose a certain option.
You want to skip validation in some cases to allow different workflows.
You want to validate a field only if the record is new or being updated.
Syntax
Ruby on Rails
validates :field_name, presence: true, if: :condition_method

# or
validates :field_name, presence: true, unless: :condition_method

# condition_method is a method that returns true or false

The if option runs validation only when the method returns true.

The unless option runs validation only when the method returns false.

Examples
This validates email only if the user is signed in.
Ruby on Rails
validates :email, presence: true, if: :email_required?

def email_required?
  user_signed_in?
end
This skips age validation if the user is an admin.
Ruby on Rails
validates :age, numericality: { greater_than: 18 }, unless: :admin?

def admin?
  role == 'admin'
end
This uses a lambda to check if the record is new before validating password presence.
Ruby on Rails
validates :password, presence: true, if: -> { new_record? }

# Uses a lambda to validate password only when creating a new record.
Sample Program

This User model requires phone_number only if contact_method is 'phone'. The example shows validation fails when phone_number is empty but contact_method is 'phone'. It passes when contact_method is 'email' even if phone_number is empty.

Ruby on Rails
class User < ApplicationRecord
  validates :phone_number, presence: true, if: :contact_by_phone?

  def contact_by_phone?
    contact_method == 'phone'
  end
end

# Example usage:
user1 = User.new(contact_method: 'phone', phone_number: '')
user2 = User.new(contact_method: 'email', phone_number: '')

puts user1.valid? # false because phone_number is required
puts user2.valid? # true because phone_number not required
OutputSuccess
Important Notes

Use simple method names for conditions to keep code readable.

Lambdas can be used for inline conditions without defining separate methods.

Conditional validations help avoid unnecessary errors and improve user experience.

Summary

Conditional validations run only when specific conditions are met.

Use if or unless with methods or lambdas.

This makes your validations flexible and context-aware.