Sunday, February 11, 2007

Ruby: Validatable

I finished up the 1.1.0 release this morning of Validatable. Validatable is a module that you can mix into your classes to add validations.
class Person
include Validatable
attr_accessor :name
validates_presence_of :name
end

person = Person.new
person.valid? #=> false
person.errors.on(:name) #=> "can't be empty"
Validatable currently supports
  • validates_presence_of
  • validates_length_of
  • validates_format_of
  • validates_confirmation_of
  • validates_acceptance_of
The validations are very similar to the validations that Rails provides. In addition to the traditional Rails functionality, Validatable provides 3 additional features.

Validation of an entire hierarchy of objects with errors aggregated at the root object.
class Person
include Validatable
validates_presence_of :name
attr_accessor :name
end

class PersonPresenter
include Validatable
include_validations_for :person
attr_accessor :person

def initialize(person)
@person = person
end
end

presenter = PersonPresenter.new(Person.new)
presenter.valid? #=> false
presenter.errors.on(:name) #=> "can't be blank"
Validations that turn off after X times of failed attempts.
class Person
include Validatable
validates_presence_of :name, :times => 1
attr_accessor :name
end

person = Person.new
person.valid? #=> false
person.valid? #=> true
Validations can be given levels. If a validation fails on a level the validations for subsequent levels will not be executed.
class Person
include Validatable
validates_presence_of :name, :level => 1, :message => "name message"
validates_presence_of :address, :level => 2
attr_accessor :name, :address
end

person = Person.new
person.valid? #=> false
person.errors.on(:name) #=> "name message"
person.errors.on(:address) #=> nil
Similar to Rails, Validatable also supports conditional validation.
class Person
include Validatable
attr_accessor :name
validates_format_of :name, :with => /.+/, :if => Proc.new { !name.nil? }
end
Person.new.valid? #=> true
Post a Comment