Last active
August 29, 2015 14:06
-
-
Save klzns/91c9c84f290106629077 to your computer and use it in GitHub Desktop.
Validação de RUC do Peru
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private bool ValidateRUC(string ruc) | |
{ | |
if (Regex.IsMatch(ruc, "^[0-9]{11}$|^[0-9]{8}$")) | |
{ | |
//converte o array de caracteres em um array de inteiros | |
int[] intArray = new int[ruc.Length]; | |
for (int i = 0; i < ruc.Length; i++) | |
{ | |
intArray[i] = Convert.ToInt32(ruc[i].ToString()); | |
} | |
if (ruc.ToString().Length == 8) | |
{ | |
var sum = 0; | |
for (int i = 0; i < intArray.Length - 1; i++) | |
{ | |
if (i == 0) | |
{ | |
sum += intArray[i] * 2; | |
} | |
else | |
{ | |
sum += (intArray[i] * (intArray.Length - i)); | |
} | |
} | |
var mod = sum % 11; | |
if (mod == 1) | |
{ | |
mod = 11; | |
} | |
if (mod + intArray[intArray.Length - 1] == 11) | |
{ | |
return true; | |
} | |
} | |
else //nessa caso tem 11 dígitos o RUC | |
{ | |
var sum = 0; | |
var x = 6; | |
for (int i = 0; i < intArray.Length - 1; i++) | |
{ | |
if (i == 4) | |
{ | |
x = 8; | |
} | |
x--; | |
sum += intArray[i] * x; | |
} | |
var mod = sum % 11; | |
mod = 11 - mod; | |
if (mod >= 10) | |
{ | |
mod -= 10; | |
} | |
if (mod == intArray[intArray.Length - 1]) | |
{ | |
return true; | |
} | |
} | |
} | |
return false; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Válidos: | |
RUC: | |
10411604646 | |
10104284138 | |
10404284199 | |
Inválidos: | |
RUC: | |
10224567888 | |
45678906543 | |
10002344567 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment