Class: MaskValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- MaskValidator
- Defined in:
- lib/mask_validator.rb
Instance Method Summary collapse
- #character_map ⇒ Object
-
#initialize(options) ⇒ MaskValidator
constructor
This validator use the characters ‘a’, ‘9’ and ‘*’ to validate the format with regular expression.
-
#mask_value_for(record = nil) ⇒ Object
Evaluate the options according with its class:.
-
#regexp(record = nil) ⇒ Object
Transform the string in a regular expression:.
- #validate_each(record, attribute, value) ⇒ Object
Constructor Details
#initialize(options) ⇒ MaskValidator
This validator use the characters ‘a’, ‘9’ and ‘*’ to validate the format with regular expression
Example using in models:
validates :phone, :mask => "(99) 9999-9999"
validates :acronym, :mask => "***"
Where:
a - to letters (A-Z, a-z)
9 - to numbers (0-9)
* - to alphanumerics (A-Z, a-z, 0-9)
16 17 18 19 20 |
# File 'lib/mask_validator.rb', line 16 def initialize() @allow_nil, @allow_blank = .delete(:allow_nil), .delete(:allow_blank) super end |
Instance Method Details
#character_map ⇒ Object
42 43 44 |
# File 'lib/mask_validator.rb', line 42 def character_map { "9" => "[0-9]", "a" => "[a-zA-Z]", "*" => "[a-zA-Z0-9]" } end |
#mask_value_for(record = nil) ⇒ Object
Evaluate the options according with its class:
[:with] = :custom_mask
[:with] = Proc.new {|o| o.custom_mask}
[:with] = "9a"
TODO: improve this
54 55 56 57 58 59 60 61 62 63 |
# File 'lib/mask_validator.rb', line 54 def mask_value_for(record=nil) case [:with] when String [:with] when Proc [:with].call(record) when Symbol record.send([:with]) end end |
#regexp(record = nil) ⇒ Object
Transform the string in a regular expression:
mask_value_for(record) => "9a"
regexp #=> /[0-9][a-zA-Z]/
TODO: improve this
38 39 40 |
# File 'lib/mask_validator.rb', line 38 def regexp(record=nil) /\A#{(mask_value_for(record).to_s.each_char.collect { |char| character_map[char] || "\\#{char}" }).join}\z/ end |
#validate_each(record, attribute, value) ⇒ Object
22 23 24 25 26 27 28 |
# File 'lib/mask_validator.rb', line 22 def validate_each(record, attribute, value) value = normalize_value(record, attribute, value) return if (@allow_nil && value.nil?) || (@allow_blank && value.blank?) record.errors.add(attribute, , ) unless value.to_s.match regexp(record) end |