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:
How to validate:
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!
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.