Avatar

Code for checking swedish "personnummer".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
  def validate_ssn
    # Kontrollera antal siffror i personnummret.
    if ssn.size != 10
      errors.add_to_base "Personnummret innehåller fel antal siffror. (ÅÅMMDDXXXX)"
    end
    
    # Räkna ut kontrollsiffran
    sum = tmp = 0

    (0..8).each do |i|
      if i % 2 == 0 
        if (tmp = 2 * ssn[i,1].to_i) > 9
          sum = sum + tmp - 9
        else
          sum = sum + tmp
        end
      else
        sum = sum + ssn[i,1].to_i
      end
    end

    if (sum % 10) != 0
      if (10 - (sum % 10)) != ssn[9,1].to_i
        errors.add_to_base 'Personnummret måste vara riktigt.'
      end
    else
      if ssn[9,1] != 0
        errors.add_to_base 'Personnummret måste vara riktigt.'
      end
    end
    
  end

Refactorings

No refactoring yet !

7f00244a6387413b37ee449f234ec045

Marc-Andre

April 7, 2009, April 07, 2009 18:26, permalink

No rating. Login to rate!

My Swedish is a bit rusty, but isn't that simply Luhn's check?
You can add all the numbers and check the sum (mod 10) is 0.
You might want to add a check that only numbers have been passed.
I didn't check the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def passes_luhn_check?(str)
  sum = 0
  numbers = str.split(//).map(&:to_i)
  numbers.each_with_index do |n, i|
    n *= 2 if i.even?
    n -= 9 if n >= 10
    sum += n
  end
  sum % 10 == 0
end

def validate_ssn
  # Kontrollera antal siffror i personnummret.
  if ssn.size != 10
    errors.add_to_base "Personnummret innehåller fel antal siffror. (ÅÅMMDDXXXX)"
  end
  
  # Räkna ut kontrollsiffran
  errors.add_to_base 'Personnummret måste vara riktigt.' unless passes_luhn_check?(ssn)
end
Avatar

Kratshi

June 23, 2009, June 23, 2009 08:48, permalink

No rating. Login to rate!

19730401

0acd844648005ae0cdd0cbb5a4a28b06

Canotooge-tool

December 5, 2009, December 05, 2009 08:23, permalink

No rating. Login to rate!

lart mycket

Your refactoring





Format Copy from initial code

or Cancel