Sterling Duchess
Sterling Duchess

Reputation: 2080

Conditional validation for ActiveModel

I have a situation where I need to validate some fields for one method and all fields for another method.

This is how my model looks at the moment:

class User < ActiveInteraction::Base

def initialize
  full_validation = true
end

# All user related auth data
string :email
string :password
string :name
string :surname
string :phone

@error
@full_validation
attr_accessor :error, :full_validation

# Validation rules
validates :email,
  presence: true,
  format: {
    with: /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/,
    :multiline => true
  }

validates :password, presence: true, length: { minimum: 6 }

validates :name, presence: true,
  format: {
    with: /^[a-zA-Z\d\s]*$/,
    :multiline => true
  }, :if => :full_validation?

validates :surname, presence: true,
  format: {
    with: /^[a-zA-Z\d\s]*$/,
    :multiline => true
  }, :if => :full_validation?

validates :phone, presence: true, :if => :full_validation?

If I call user = User.new and then call user.full_validation = false then only email and password fields should be validated however the if statements in the validation for name, surname and phone completely ignore this and return validation errors.

I also tried few other approaches all work (no errors) but still validate all fields:

def isFullValidation
  full_validation == true
end

I also tried using with_options and wrap the 3 validation rules in if: :full_validation? do .. end statement.

Upvotes: 1

Views: 367

Answers (1)

iMacTia
iMacTia

Reputation: 671

Try using grouping conditional validation

with_options if: Proc.new { |u| u.is_full_validation? } do |user|
  user.validates ... # pay attention to the 'user.' in front of each validation!!
  user.validates ...
end

def is_full_validation?
  full_validation == true
end

Upvotes: 1

Related Questions