Class: AlphaNumericValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/rails/alpha_numeric_validator.rb

Constant Summary collapse

PUNCTUATION_REGEXP =
{
default: /(?:[[:alpha:]]|[[:digit:]])+/,
:true => /(?:[[:graph:]])+/,
limited: /(?:[[:alpha:]]|[[:digit:]]|[_:\+\.\?,\-!'\/#])+/, # ' vim-color-syntax hack
dns: /(?:[[:alpha:]]|[[:digit:]]|[\.\-])+/,
fqdn: /(?:[[:alpha:]]|[[:digit:]]|-|\.)+/}
WHITESPACE_EXCEPTIONS =
[:dns, :fqdn]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ AlphaNumericValidator

Creation

To use the AlphaNumericValidator, initialize it as any other class

class ExampleValidator < ActiveRecord::Base
  validates :attr1, alpha_numeric: true
  validates :attr2, alpha_numeric: {punctuation: true}
  validates :attr3, alpha_numeric: {punctuation: :limited}
  validates :attr4, alpha_numeric: {allow_whitespace: true}
  validates :attr4, alpha_numeric: {dns: true}
end


27
28
29
30
31
# File 'lib/rails/alpha_numeric_validator.rb', line 27

def initialize(*args) # :nodoc:
  @errors = []
  @record = nil
  super(*args)
end

Instance Attribute Details

#stringObject

:nodoc:



5
6
7
# File 'lib/rails/alpha_numeric_validator.rb', line 5

def string
  @string
end

Instance Method Details

#has_whitespace?Boolean

:call-seq: has_whitespace?

returns true if the string contains whitespace

Returns:

  • (Boolean)


80
81
82
# File 'lib/rails/alpha_numeric_validator.rb', line 80

def has_whitespace?
  @string.to_s.match /(?:\s)+/
end

#is_valid?Boolean

:call-seq: is_valid?

alias for :is_valid_string?

Returns:

  • (Boolean)


58
59
60
# File 'lib/rails/alpha_numeric_validator.rb', line 58

def is_valid?
  is_valid_string?
end

#is_valid_string?Boolean

:call-seq: is_valid_string?

returns true if the string only contains the requested character set

TODO: support international DNS

Returns:

  • (Boolean)


69
70
71
72
73
# File 'lib/rails/alpha_numeric_validator.rb', line 69

def is_valid_string?
  return false if !@options[:allow_whitespace] && has_whitespace?
  re = PUNCTUATION_REGEXP[@options[:punctuation].to_s.to_sym]
  @string.to_s.gsub(re, "").blank?
end

#validate_each(record, attribute, value) ⇒ Object

:call-seq: validate_each :record, :attribute, :value

:record

AR instance

:attribute

symbol for attribute

:value

value to check validity



40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/rails/alpha_numeric_validator.rb', line 40

def validate_each(record, attribute, value) #:nodoc:
  @record = record
  opts = {punctuation: :default}
  opts.merge! allow_whitespace: !WHITESPACE_EXCEPTIONS.member?(@options[:punctuation])
  @options = opts.merge @options

  # TODO: document why value[1]
  @string = value.is_a?(Array) ? value[1] : value
  unless @string.nil? || @string.class.ancestors.include?(Numeric) || is_valid?
    record.errors[attribute] << 'invalid characters'
  end
end