Jump to content

Check if credit card number is valid ?


nobitavn94

Recommended Posts

try somehtign like this

System.String creditCard = (System.String) values[0];// strip out non-numeric charactersSystem.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex("[^0-9]");System.String numbers = re.Replace(creditCard, "");// Return the credit card number with only the digits in the stringresult = numbers;// The algorithm to validate a credit card is this// 1) Start from the right, and remove every second digit// 2) Double each of these values// 3) Add each digit in each doubled value together (12 becomes 3, for example)// 4) Add these values back to the remaining digits in the credit card number// 5) Verify that the result is a multiple of 10int total = 0;for (int i = numbers.Length - 2; i >= 0; i -= 2){int num = System.Convert.ToInt32(numbers[i] + "");// double itnum *= 2;// add the digitswhile (num >= 10){total += (num % 10);num = num / 10;}// add to totaltotal += num;}// now add on the unused digitsfor (int i = numbers.Length - 1; i >= 0; i -= 2){total += System.Convert.ToInt32(numbers[i] + "");}if ((total % 10) != 0){throw new System.Exception("Credit card number " + creditCard + " is not valid. The checksum is incorrect.");}

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...