Class: NotNaughty::FormatValidation

Inherits:
Validation show all
Defined in:
lib/not_naughty/validations/format_validation.rb

Overview

Validates format of obj’s attribute via the :match method.

Unless the validation succeeds an error hash (:attribute => :message) is added to the obj’s instance of Errors.

Options:

:with

object that checks via a :match call

:message

see NotNaughty::Errors for details

:if

see NotNaughty::Validation::Condition for details

:unless

see NotNaughty::Validation::Condition for details

Example:

obj = 'abc'
def obj.errors() @errors ||= NotNauthy::Errors.new end

FormatValidation.new({:with => /[a-z]/}, :to_s).call obj, :to_s, obj
obj.errors.on(:to_s).any? # => false

FormatValidation.new({:with => /[A-Z]/}, :to_s).call obj, :to_s, obj
obj.errors.on(:to_s) # => ["Format of to_s does not match."]

Use predefined format expressions:

obj = 'Valid Address <[email protected]>'
def obj.errors() @errors ||= NotNauthy::Errors.new end

FormatValidation.new({:with => :email}, :to_s).call obj, :to_s, obj
obj.errors.on(:to_s).any? # => false

Direct Known Subclasses

NumericalityValidation

Constant Summary collapse

PREDEFINED =

Predefined matchers.

{
  :email => /[a-z0-9!#\$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#\$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/,
  :ip => /(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/
}

Constants inherited from Validation

Validation::PATTERN

Instance Attribute Summary

Attributes inherited from Validation

#attributes

Instance Method Summary collapse

Methods inherited from Validation

#call_with_conditions, #call_without_conditions, inherited, load, load_paths, new

Constructor Details

#initialize(valid, attributes) ⇒ FormatValidation

:nodoc:



40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/not_naughty/validations/format_validation.rb', line 40

def initialize(valid, attributes) #:nodoc:
  valid[:with] = PREDEFINED.fetch valid[:with] if valid[:with].is_a? Symbol
  valid[:with].respond_to? :match or
  raise ArgumentError, "#{ valid[:with].inspect } doesn't :match"

  valid[:message] ||= '%s does not match format.'

  if valid[:allow_blank] || valid[:allow_nil]
    valid[:allow] = valid[:allow_blank] ? :blank? : :nil?
    super valid, attributes, &matching_block_with_exception(valid)
  else
    super valid, attributes, &matching_block(valid)
  end
end