Hoje vou começar uma nova categoria de artigos, denominada de utilidades. O objectivo desta categoria será fornecer pequenas funções que nos possam ajudar no desenvolvimento de aplicações.
Neste artigo vou demonstrar como podemos efectuar a validação de um número de contribuinte.
O número de contribuinte é constituÃdo por 9 algarismos, dos quais o último é um algarismo de validação, uma espécie de checksum. A função que vamos desenvolver hoje efectua estas duas validações (9 algarismos e CheckBit).
Em C#, a função de validação é a seguinte:
/// <summary>
/// Validates a NIF (Número de Identificação Fiscal)
/// </summary>
/// <param name=”nif”></param>
/// <returns></returns>
public static bool IsValidNIF(string nif)
{
//Check if is numeric and if has 9 numbers
if (Utils.IsNumeric(nif) && nif.Length == 9)
{
//Get the first number of NIF
char c = nif[0];
//Check firt number is (1, 2, 5, 6, 8 or 9)
if (c.Equals(’1′) || c.Equals(’2′) || c.Equals(’5′) || c.Equals(’6′) || c.Equals(’8′) || c.Equals(’9′))
{
//Perform CheckDigit calculations
int checkDigit = (Convert.ToInt32(c.ToString()) * 9);
for (int i = 2; i <= 8; i++)
{
checkDigit += Convert.ToInt32(nif[i - 1].ToString()) * (10 - i);
}
checkDigit = 11 - (checkDigit % 11);
//if checkDigit is higher than ten set it to zero
if (checkDigit >= 10) checkDigit = 0;
//Compare checkDigit with the last number of NIF
//If equal the NIF is Valid.
if (checkDigit.ToString() == nif[8].ToString()) return true;
}
}
return false;
}
}
//###Class Utils###
/// <summary>
/// Test if a String is Numeric
/// </summary>
/// <param name=”inputString”></param>
/// <returns></returns>
public static bool IsNumeric(string inputString)
{
return Regex.IsMatch(inputString, “^[0-9]+$”);
}
Esta função é usada para efectuar a validação no codebehind. Para efectuarmos a validação com a ajuda dos validators do ASP.NET usamos a mesma função mas em javascript:
function IsValidNIF(nif)
{
var c;
var checkDigit = 0;
//Check if is not null, is numeric and if has 9 numbers
if(nif != null && IsNumeric(nif) && nif.length == 9)
{
//Get the first number of NIF
c = nif.charAt(0);
//Check firt number is (1, 2, 5, 6, 8 or 9)
if(c == ‘1′ || c == ‘2′ || c == ‘5′ || c == ‘6′ || c == ‘8′ || c == ‘9′)
{
//Perform CheckDigit calculations
checkDigit = c * 9;
var i = 0;
for(i = 2; i <= 8; i++)
{
checkDigit += nif.charAt(i-1) * (10-i);
}
checkDigit = 11 - (checkDigit % 11);
//if checkDigit is higher than ten set it to zero
if(checkDigit >= 10)
checkDigit = 0;
//Compare checkDigit with the last number of NIF
//If equal the NIF is Valid.
if(checkDigit == nif.charAt(8))
return true;
}
}
return false;
}
function IsNumeric(ObjVal)
{
return /^\d+$/.test(ObjVal);
}
No link seguinte podem efectuar o download de um pequeno projecto, onde podem testar estas duas funções.
http://www.megaupload.com/?d=7Q1VXMNV
Qualquer dúvida, deixem um comentário, terei todo o prazer em ajudar.




Últimos Comentários