Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a single validation in Rails

I'm sending friends invitations and I want to validate email address using User.validates_format_of :email, except that User.email has a couple of other validations which I'm not really interested in.

So is there a way to run a single validation on a model or check if that specific validation has passed (without doing user.errors.include?(validation_message) )?

like image 560
squil Avatar asked Oct 05 '09 09:10

squil


3 Answers

You can check the gem grouped_validations

class Person < ActiveRecord::Base
  validation_group :name do
    validates_presence_of :first_name
    validates_presence_of :last_name
  end
  validates_presence_of :sex
end

Then you can do this in your controller

p = Person.new
p.group_valid?(:name) # => false
p.first_name = 'John'
p.last_name = 'Smith'
p.group_valid?(:name) # => true
like image 143
Moustafa Samir Avatar answered Nov 01 '22 00:11

Moustafa Samir


Create a method like this in your model and use it for partial validation

def has_valid_name?
  valid? || (errors[:first_name].empty? && errors[:last_name].empty?)
end
like image 34
Mika Avatar answered Oct 31 '22 23:10

Mika


You can check if a specific error has been added:

user.errors.added? :name, :blank
like image 27
Clemens Helm Avatar answered Oct 31 '22 23:10

Clemens Helm