Valid8ors brings you a nice set of custom validators for Rails 3.
Add this line to your Gemfile:
gem 'valid8ors'
Then run:
bundle install
Check that an attribute doesn't contain blacklisted values.
class User < ActiveRecord::Base
validates :name, blacklist: true
end
You can create a blacklist.yml file in the config directory of your Rails application if you need to overload the one used by this gem.
Key to translate: :blacklisted. Hence, considering the example above, the translation path would be:
en.activerecord.errors.models.user.attributes.name.blacklisted
Validate an attribute against a reserved list of values.
class User < ActiveRecord::Base
validates :name, reserved: true
end
You can create a reserved.yml file in the config directory of your Rails application if you need to overload the one used by this gem.
Key to translate: :reserved. Hence, considering the example above, the translation path would be:
en.activerecord.errors.models.user.attributes.name.reserved
class User < ActiveRecord::Base
validates :email, email_format: true
end
Restrict your validation to specific domains:
class User < ActiveRecord::Base
validates :email, email_format: { domains: ['gmail.com', 'live.com'] }
end
Keys to translate: :improperly_formatted (when not an email format) and :invalid_domain (when email domain not listed in "domains" option). Hence, considering the two examples above, translation paths would be:
en.activerecord.errors.models.user.attributes.email.improperly_formatted
en.activerecord.errors.models.user.attributes.email.invalid_domain
Regular Expression tests based on Comparing E-mail Address Validating Regular Expressions
class User < ActiveRecord::Base
validates :url, url_format: true
end
Key to translate: :improperly_formatted. Hence, considering the example above, the translation path would be:
en.activerecord.errors.models.user.attributes.url.improperly_formatted
Check if a password contains at least a digit, lowercase and uppercase letter. Password length validation is not included here as you can use Rails' builtin "LengthValidator".
class User < ActiveRecord::Base
validates :password, password_strength: true
end
Key to translate: :insecure. Hence, considering the example above, the translation path would be:
en.activerecord.errors.models.user.attributes.password.insecure
By default, checks if an attribute is nil. Use allow_blank option to accept empty objects.
class User < ActiveRecord::Base
validates :name, absence: true # Validate name is nil
validates :email, absence: { allow_blank: true } # Validate email is blank
end
Key to translate: :not_absent. Hence, considering the example above, translation paths would be:
en.activerecord.errors.models.user.attributes.name.not_absent
en.activerecord.errors.models.user.attributes.email.not_absent
rake test
Ruby version >= 1.9.x