Class: MxitRails::Validations

Inherits:
Object
  • Object
show all
Defined in:
lib/mxit_rails/validations.rb

Class Method Summary collapse

Class Method Details

.cellphone_number?(input) ⇒ Boolean

Returns:

  • (Boolean)


33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/mxit_rails/validations.rb', line 33

def self.cellphone_number? input
  return false unless numeric?(input)

  # Normalise to local 0xx format
  input.sub! /^00/, '0'
  input.sub! /^\+/, ''
  input.sub! /^27/, '0'

  # Check length is 10, and first digits are 07 or 08
  return false unless length?(input, 10)
  return false unless ((input =~ /^07/) || (input =~ /^08/))

  return true
end

.length?(input, len) ⇒ Boolean

Returns:

  • (Boolean)


13
14
15
# File 'lib/mxit_rails/validations.rb', line 13

def self.length? input, len
  return !input.blank? && (input.length == len)
end

.max_length?(input, max) ⇒ Boolean

Returns:

  • (Boolean)


21
22
23
# File 'lib/mxit_rails/validations.rb', line 21

def self.max_length? input, max
  return input.blank? || (input.length <= max)
end

.max_value?(input, max) ⇒ Boolean

Returns:

  • (Boolean)


29
30
31
# File 'lib/mxit_rails/validations.rb', line 29

def self.max_value? input, max
  return input.to_f <= max
end

.min_length?(input, max) ⇒ Boolean

Returns:

  • (Boolean)


17
18
19
# File 'lib/mxit_rails/validations.rb', line 17

def self.min_length? input, max
  return !input.blank? && (input.length >= max)
end

.min_value?(input, min) ⇒ Boolean

Returns:

  • (Boolean)


25
26
27
# File 'lib/mxit_rails/validations.rb', line 25

def self.min_value? input, min
  return input.to_f >= min
end

.not_blank?(input) ⇒ Boolean

Returns:

  • (Boolean)


4
5
6
# File 'lib/mxit_rails/validations.rb', line 4

def self.not_blank? input
  return !input.blank?
end

.numeric?(input) ⇒ Boolean

Returns:

  • (Boolean)


8
9
10
11
# File 'lib/mxit_rails/validations.rb', line 8

def self.numeric? input
  input.gsub! /\s*/, ''
  return !input.blank? && input.match(/^[0-9]+$/)
end

.sa_id_number?(input) ⇒ Boolean

Returns:

  • (Boolean)


48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/mxit_rails/validations.rb', line 48

def self.sa_id_number? input
  return false unless numeric?(input)

  #1. numeric and 13 digits
  return false unless length?(input, 13)

  #2. first 6 numbers is a valid date
  dateString = "#{input[0..1]}-#{input[2..3]}-#{input[4..5]}"
  begin
    date = Date.parse dateString
  rescue ArgumentError
    return false
  end

  #3. luhn formula
  temp_total = 0
  checksum = 0
  multiplier = 1
  (0..12).each do |i|
    temp_total = input[i].to_i * multiplier
    if temp_total > 9
      temp_total = temp_total.to_s[0].to_i + temp_total.to_s[1].to_i
    end
    checksum += temp_total
    multiplier = multiplier.even? ? 1 : 2
  end
  return checksum % 10 == 0
end