Louche adds common validators for ActiveModel/ActiveRecord classes.
Installation
Add this line to your application's Gemfile:
gem 'louche'
Usage
Louche provides a few validators to use in your ActiveModel/ActiveRecord classes:
EmailValidator
class User < ActiveRecord::Base
validates :email, email: true
end
User.new(email: '[email protected]').valid? # => true
User.new(email: 'foo@example').valid? # => false
URLValidator
class User < ActiveRecord::Base
validates :website, url: true
end
User.new(website: 'http://example.com').valid? # => true
User.new(website: 'example.$$$').valid? # => false
PhoneNumberValidator
class User < ActiveRecord::Base
validates :phone_number, phone_number: true
end
user = User.new(phone_number: '514 555-2525')
user.valid? # => true
user.phone_number # => '5145552525'
user = User.new(phone_number: '555-2525')
user.valid? # => false
user.phone_number # '5552525'
PostalCodeValidator
class User < ActiveRecord::Base
validates :postal_code, postal_code: true
end
user = User.new(postal_code: 'G0R 2T0')
user.valid? # => true
user.postal_code # => 'G0R2T0'
user = User.new(postal_code: 'L -0- L')
user.valid? # => false
user.postal_code # => 'L0L'
ArrayValidator
class Tag < Struct.new(:name)
def valid?
name.present?
end
end
class User < ActiveRecord::Base
validates :tags, array: true
def ()
super .map { |tag| Tag.new(tag) }
end
end
User.new(tags: ['food', 'beer', 'code']).valid? # => true
User.new(tags: ['food', '', 'code']).valid? # => false
License
Louche
is © 2014 Mirego and may be freely distributed under the New BSD license. See the LICENSE.md
file.
About Mirego
Mirego is a team of passionate people who believe that work is a place where you can innovate and have fun. We're a team of talented people who imagine and build beautiful Web and mobile applications. We come together to share ideas and change the world.
We also love open-source software and we try to give back to the community as much as we can.