IsValidNIP, IsValidREGON, IsValidPESEL

public static class Validators
{
    public static bool IsValidNIP(this string input)
    {
        int[] weights = { 6, 5, 7, 2, 3, 4, 5, 6, 7 };
        bool result = false;
        if (input.Length == 10)
        {
            int controlSum = CalculateControlSum(input, weights);
            int controlNum = controlSum % 11;
            if (controlNum == 10)
            {
                controlNum = 0;
            }
            int lastDigit = int.Parse(input[input.Length - 1].ToString());
            result = controlNum == lastDigit;
        }
        return result;
    }

    public static bool IsValidREGON(this string input)
    {
        int controlSum;
        if (input.Length == 7 || input.Length == 9)
        {
            int[] weights = { 8, 9, 2, 3, 4, 5, 6, 7 };
            int offset = 9 - input.Length;
            controlSum = CalculateControlSum(input, weights, offset);
        }
        else if (input.Length == 14)
        {
            int[] weights = { 2, 4, 8, 5, 0, 9, 7, 3, 6, 1, 2, 4, 8 };
            controlSum = CalculateControlSum(input, weights);
        }
        else
        {
            return false;
        }
            
        int controlNum = controlSum % 11;
        if (controlNum == 10)
        {
            controlNum = 0;
        }
        int lastDigit = int.Parse(input[input.Length - 1].ToString());

        return controlNum == lastDigit;
    }

    public static bool IsValidPESEL(this string input)
    {
        int[] weights = { 1, 3, 7, 9, 1, 3, 7, 9, 1, 3 };
        bool result = false;
        if (input.Length == 11)
        {
            int controlSum = CalculateControlSum(input, weights);
            int controlNum = controlSum % 10;
            controlNum = 10 - controlNum;
            if (controlNum == 10)
            {
                controlNum = 0;
            }
            int lastDigit = int.Parse(input[input.Length - 1].ToString());
            result = controlNum == lastDigit;
        }
        return result;
    }

    private static int CalculateControlSum(string input, int[] weights, int offset = 0)
    {
        int controlSum = 0;
        for (int i = 0; i < input.Length - 1; i++)
        {
            controlSum += weights[i + offset] * int.Parse(input[i].ToString());
        }
        return controlSum;
    }
}
Example:
string nip = "1234567890";
string regon = "123456789";
string pesel = "12345678901";

Console.WriteLine(nip.IsValidNIP() ? "NIP is valid" : "NIP is not valid");
Console.WriteLine(regon.IsValidREGON() ? "REGON is valid" : "REGON is not valid");
Console.WriteLine(pesel.IsValidPESEL() ? "PESEL is valid" : "PESEL is not valid");

Description

Validation algorithms for Polish identification numbers NIP, REGON & PESEL.

Details

Double click on the code to select all.

 

;