Module: StringMagic::Core::Validation

Included in:
String, StringMagic
Defined in:
lib/string_magic/core/validation.rb

Instance Method Summary collapse

Instance Method Details

#anagram_of?(other) ⇒ Boolean

Returns:

  • (Boolean)


50
51
52
53
54
55
# File 'lib/string_magic/core/validation.rb', line 50

def anagram_of?(other)
  return false if other.nil? || other.empty?

  norm = ->(s) { s.downcase.gsub(/[^a-z0-9]/, '').chars.sort.join }
  !empty? && norm.call(self) == norm.call(other)
end

#credit_card?Boolean


Credit-card number (Luhn)


Returns:

  • (Boolean)


29
30
31
32
33
34
35
36
37
38
39
# File 'lib/string_magic/core/validation.rb', line 29

def credit_card?
  digits = gsub(/\D/, '')
  return false unless (13..19).cover?(digits.length)

  sum = digits.reverse.chars.each_with_index.sum do |ch, idx|
    n = ch.to_i
    n *= 2 if idx.odd?
    n > 9 ? n - 9 : n
  end
  (sum % 10).zero?
end

#email?Boolean


Basic format checks


Returns:

  • (Boolean)


12
13
14
# File 'lib/string_magic/core/validation.rb', line 12

def email?
  !!(self =~ /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i)
end

#integer?Boolean

Returns:

  • (Boolean)


65
66
67
# File 'lib/string_magic/core/validation.rb', line 65

def integer?
  !!(self =~ /\A-?\d+\z/)
end

#numeric?Boolean


Number checks


Returns:

  • (Boolean)


61
62
63
# File 'lib/string_magic/core/validation.rb', line 61

def numeric?
  !!(self =~ /\A-?(?:\d+\.?\d*|\.\d+)\z/)
end

#palindrome?Boolean


Text relationships


Returns:

  • (Boolean)


45
46
47
48
# File 'lib/string_magic/core/validation.rb', line 45

def palindrome?
  cleaned = downcase.gsub(/[^a-z0-9]/, '')
  cleaned == cleaned.reverse && !cleaned.empty?
end

#phone?Boolean

Returns:

  • (Boolean)


20
21
22
23
# File 'lib/string_magic/core/validation.rb', line 20

def phone?
  digits = gsub(/\D/, '')
  (10..15).cover?(digits.length)
end

#strong_password?(min_length: 8) ⇒ Boolean


Password strength


Returns:

  • (Boolean)


73
74
75
76
77
78
79
80
# File 'lib/string_magic/core/validation.rb', line 73

def strong_password?(min_length: 8)
  return false if length < min_length

  /[A-Z]/.match?(self) &&
    /[a-z]/.match?(self) &&
    /\d/.match?(self) &&
    /[^A-Za-z0-9]/.match?(self)
end

#url?Boolean

Returns:

  • (Boolean)


16
17
18
# File 'lib/string_magic/core/validation.rb', line 16

def url?
  !!(self =~ /\A#{URI::DEFAULT_PARSER.make_regexp(%w[http https])}\z/)
end