.net - Convert algorithm to validate NIPC / NIF into a C# Regex (Regular Expression) -
i've got next simple algorithm validate nipc / nif identification portugal:
private bool isnipccorrect(string nifstring) { int controldigit = 0; (int = 0; < nifstring.length - 1; i++) { controldigit += (int)char.getnumericvalue(nifstring[i]) * (10 - - 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 know if generate little regex validate identification in few lines.
initial validation:
- lenght: 9 digits
- control digit: nifstring[8]
how validate:
- 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
- if(sum % 11 <= 1) controldigit = 0
- else controldigit = 11 - (sum % 11)
- then check if(controldigit == nifstring[8])
i've been thinking in next initial pattern = [0-9]{9}|\d{9}
but how use regex final validations too?
regards!
regex can't calculation suitable code check against first ^\d{9}$
you need make check before run rest of code if string not have 9 characters in error @ point nifstring[8]
so invalid nif of 12345 result in error rather return of false.
Comments
Post a Comment