Class: AccountNameValidator Abstract
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- AccountNameValidator
- Defined in:
- lib/account_name_validator.rb
Overview
Subclass this validator to perform your specific account name validations.
Generic @EachValidator@ that validates account names on various communication services such as Skype, Yahoo!, etc. This class provides a simple DSL for describing valid account names on these sites, performing all validation for you.
Subclass this class and use the provided DSL to describe account names on a given site. An example for a fictional service called Talkalot:
<pre><code> class TalkalotValidator < AccountNameValidator
min_length 5
max_length 64
valid_chars "A-Z0-9_"
end </code></pre>
With your validator defined you can now use it in your Active Record models like any other @EachValidator@:
<pre><code>
validates :talkalot_id,
talkalot: true
</code></pre>
This class automatically handles the following options passed to the @validates@ method:
| @:allow_nil@ | Allows @nil@ values. | | @:message@ | Provide a custom error message. |
Error messages generated by this class are stored in the translation table. The localization keys used are generated by the @ActiveModel::Errors#generate_message@ method (see its documentation for more information). The lastmost element of the localization key is the error message key. The error message key is a combination of a validator subclass’s AccountNameValidator.error_key_prefix and the error key suffix for a given constraint.
By default the error key prefix is the underscored
As an example, for the @TalkalotValidator@ example above, the error message key used in the event that a two-letter account name is given would be @:talkalot_too_short@. If you wanted to override the prefix, you could do:
<pre><code> class TalkalotValidator < AccountNameValidator
error_key_prefix :talky
end </code></pre>
In this case the error message key for a two-letter account name would be @:talky_too_short@. (You’d do this if Talkalot accounts were called “talkies,” for example.)
Direct Known Subclasses
AimValidator, SkypeValidator, SteamValidator, XboxLiveValidator, YahooImValidator
Instance Method Summary collapse
Instance Method Details
#validate_each(record, attribute, value) ⇒ Object
62 63 64 65 66 67 |
# File 'lib/account_name_validator.rb', line 62 def validate_each(record, attribute, value) return if [:allow_nil] and value.nil? return if [:allow_blank] and value.blank? return unless self.class.validations self.class.validations.each { |block, key| record.errors.add(attribute, [:message] || record.errors.(attribute, :"#{self.class.error_key_prefix}_#{key}")) if !block[value.to_s] } end |