using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Text.RegularExpressions;
public partial class luhn : System.Web.UI.Page
{
public string numberToVerify = "";
public int ttlAddition = 0, cpt = 1;
public StringBuilder sb = new StringBuilder();
protected void Page_Load(object sender, EventArgs e)
{
numberToVerify = Request["numberToVerify"] ?? "";
if (numberToVerify != "")
{
string formatInput = Regex.Replace(numberToVerify, "[^a-zA-Z0-9_]+", "", RegexOptions.Compiled);
string reverseCard = new string(formatInput.ToCharArray().Reverse().ToArray());
int[] arrDigits = Array.ConvertAll<string, int>(
System.Text.RegularExpressions.Regex.Split(reverseCard.ToString(), @"(?!^)(?!$)"),
str => int.Parse(str)
);
int[] arrMult = new int[arrDigits.Length];
// première étape de Luhn : On démarre avec le dernier chiffre (à droite) et on se déplace vers la gauche, en doublant la valeur de tous les chiffres de rang pair
for (int i = 0; i < arrDigits.Length; i++)
{
if (cpt == 1)
arrMult[i] = arrDigits[i]; // la clé est traitée en 1er, le chiffre n'est pas doublé
else
{
if (cpt % 2 == 0)
arrMult[i] = 2 * arrDigits[i];
else
arrMult[i] = arrDigits[i];
}
cpt++;
}
// On additionne ensemble tous les chiffres de chaque nombre ainsi obtenu, si chiffre > 10 alors chiffre à additionner donne par ex : 18 = 1 + 8
for (int i = 0; i < arrMult.Length; i++)
{
if ((int)arrMult[i] >= 10) // si chiffre > 9 il faut re décomposer le chiffre, ex 18 donne : 1+8
{
int[] intList = Array.ConvertAll<string, int>(
System.Text.RegularExpressions.Regex.Split(arrMult[i].ToString(), @"(?!^)(?!$)"),
str => int.Parse(str)
);
for (int j = 0; j < intList.Count(); j++)
{
ttlAddition += (int)intList[j];
}
}
else
ttlAddition += (int)arrMult[i];
}
// si modulo par 10 de l'addition est nul alors notre chiffre est valide
if (ttlAddition % 10 == 0)
spanResult.InnerHtml = "Vérification OK";
else
spanResult.InnerHtml = "Vérification Fausse";
}
}
}