Skip to content

Instantly share code, notes, and snippets.

@yemrekeskin
Created May 11, 2013 18:44
Show Gist options
  • Save yemrekeskin/5560949 to your computer and use it in GitHub Desktop.
Save yemrekeskin/5560949 to your computer and use it in GitHub Desktop.
Enterprise Code #1: Validation for Credit Card Numbers
/// <summary>
/// Validation provider by luhn Algorithm
/// </summary>
public static class CreditCardNumberExtention
{
public const int DIGIT_NUM = 16;
public static bool IsValidCreditCardNumber(this string accountNumber)
{
if (String.IsNullOrEmpty(accountNumber))
throw new FormatException(RC.GetString("EmptyAccNumber"));
if (DIGIT_NUM != accountNumber.Length)
throw new FormatException(RC.GetString("AccNumberMaxDigit"));
int singleIndexValue = 0;
int doubleIndexValue = 0;
for (int i = 0; i < accountNumber.Length; i++)
{
int indexValue = int.Parse(accountNumber[i].ToString());
if (i % 2 == 0)
doubleIndexValue += SumDigit(indexValue * 2);
else
singleIndexValue += indexValue;
}
return (singleIndexValue + doubleIndexValue) % 10 == 0 ? true : false;
}
private static int SumDigit(int value)
{
int sum = 0;
while (value > 0)
{
sum += value % 10;
value /= 10;
}
return sum;
}
}
public static class RC // Resource Control
{
public static string GetString(string key)
{
Dictionary<string, string> StringSource = new Dictionary<string, string>();
StringSource.Add("EmptyAccNumber", "Account Number must not be empty");
StringSource.Add("AccNumberMaxDigit", "Account Number must be 16 digit");
// Normally this resource strings should get from another data source(txt,database etc.)
string value = StringSource.Where(d => d.Key == key).ToString();
return String.IsNullOrEmpty(value) ? String.Empty : value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment