Custom Rails Validations

I’ve been having some trouble getting custom rails validations to work after reading Peter Marklund’s post on the topic. I finally have a configuration that works, and I’m posting it up here because

  1. I’ve read some random posts and threads about problems with this, and
  2. Because randomly this configuration seems to stop working for me.

So here it is. (Thanks to Peter for the actual validation technique.)

app/models/listing.rb:

def validate
 	validate_phone('phone')
end

lib/iociem/validations.rb:

require 'active_record'
 
module Iociem
 
  module Validations
 
    def validate_phone(*attributes)
      error_message = 'is an invalid phone number, must contain at least 5 digits, only the following characters are allowed: 0-9/-()+'
      attributes.each do |attribute|
        self.errors.add(attribute, error_message) unless valid_phone?(self.send(attribute))
      end
    end
 
    def valid_phone?(number)
      return true if number.nil?
      n_digits = number.scan(/[0-9]/).size
      valid_chars = (number =~ /^[+/-() 0-9]+$/)
      return n_digits > 5 && valid_chars
    end
 
  end
 
end
 
class ActiveRecord::Base
  include Iociem::Validations
end

EDIT: Yup, and it stopped working.

Undefined method validate_phone for <Listing:0xDEADBEEF>

What the hell? It’s probably about now that I should start looking into actually using the testing parts of Rails.

EDIT 2: I think this works for now. I moved this code to my environment.rb:

class ActiveRecord::Base
  include Iociem::Validations
end

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*