2

I'm looking for a clean and efficient way to validate an Israeli ID number.

It's basically an implementation of the Luhn algorithm on a 9 digits number.

Note: This question is here for the community because it wasn't on stack overflow yet. You can add answers in different coding languages.

Milana
  • 557
  • 9
  • 20

2 Answers2

1

Here's an efficient way to implement it in C# (link):

public static bool IsValidIsraeliID(string israeliID)
    {
        if (israeliID.Length != 9)
            return false;

        long sum = 0;

        for (int i = 0; i < israeliID.Length; i++)
        {
            var digit = israeliID[israeliID.Length - 1 - i] - '0';
            sum += (i % 2 != 0) ? GetDouble(digit) : digit;
        }

        return sum % 10 == 0;

        int GetDouble(long i)
        {
            switch (i)
            {
                case 0: return 0;
                case 1: return 2;
                case 2: return 4;
                case 3: return 6;
                case 4: return 8;
                case 5: return 1;
                case 6: return 3;
                case 7: return 5;
                case 8: return 7;
                case 9: return 9;
                default: return 0;
            }
        }
    }
Milana
  • 557
  • 9
  • 20
1

JS example code like it appears in Wikipedia: https://he.wikipedia.org/wiki/ספרת_ביקורת

function IDValidator(id)
{
    if (id.length !== 9 || isNaN(id)) {  // Make sure ID is formatted properly
        return false;
    }
    let sum = 0, incNum;
    for (let i = 0; i < id.length; i++) {
        incNum = Number(id[i]) * ((i % 2) + 1);  // Multiply number by 1 or 2
        sum += (incNum > 9) ? incNum - 9 : incNum;  // Sum the digits up and add to total
    }
    return (sum % 10 === 0);
}
Asaf M
  • 274
  • 2
  • 9