myowin76
7/19/2013 - 11:21 AM

rails3 custom validation

rails3 custom validation

validates_format_of :ssn,
  :with => /^[\d]{3}-[\d]{2}-[\d]{4}$/, 
  :message => "must be of format ###-##-####"
  
====================================================
// lib/custom_validations.rb

module CustomValidations
  def validates_ssn(*attr_names)
    attr_names.each do |attr_name| validates_format_of attr_name,
      :with => /^[\d]{3}-[\d]{2}-[\d]{4}$/,
      :message => "must be of format ###-##-####"
    end 
  end
end
ActiveRecord::Base.extend(CustomValidations)

// config/environment.rb
require 'custom_validations'

// model/student.rb

class Student < ActiveRecord::Base 
  validates_presence_of :name 
  validates_ssn :ssn
end