Search code examples
c#.netregexvalidationidentification

Convert algorithm to validate NIPC / NIF into a C# Regex (Regular Expression)


I've got the next simple algorithm to validate the NIPC / NIF identification for Portugal:

private bool IsNIPCCorrect(String nifString)
    {
        int controlDigit = 0;

        for (int i = 0; i < nifString.Length - 1; i++)
        {
            controlDigit += (int)Char.GetNumericValue(nifString[i]) * (10 - i - 1);
        };

        controlDigit = controlDigit % 11;

        if (controlDigit <= 1)
        {
            controlDigit = 0;
        }
        else
        {
            controlDigit = 11 - controlDigit;
        }

        if (controlDigit == (int)Char.GetNumericValue(nifString[8]))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

I'd like to know if I could generate a little Regex to validate that identification in few lines.

Initial validation:

  • Lenght: 9 digits
  • Control digit: nifString[8]
  • How to validate:

    1. sum = nifString[7] * 2 + nifString[6] * 3 + nifString[5] * 4 + nifString[4] * 5 + nifString[3] * 6 + nifString[2] * 7 + nifString[1] * 8 + nifString[0] * 9
      1. if(sum % 11 <= 1) controlDigit = 0
      1. else controlDigit = 11 - (sum % 11)
    2. then check if(controlDigit == nifString[8])

I've been thinking in something like the next initial pattern = [0-9]{9}|\d{9}

But how could I use only Regex for the final validations too?

Regards!


Solution

  • Regex can't do the calculation for you but a suitable code to check against first is ^\d{9}$

    You need to make this check before you run the rest of the code as if the string does not have 9 characters in it you will get an error at the point nifString[8]

    So an invalid NIF of 12345 would result in an error rather than a return of false.