/** * Checks if the value is a valid credit card number * @param value a string * @return true if the value is a valid credit card number */ public static boolean isValid(String value){ return luhnCheck(value.replaceAll("\\D", "")); //remove non-digits } /** * Checks if a cardNumber passes LUHN check * @param cardNumber A string contains only digits * @return true if the cardNumber passes LUHN check */ private static boolean luhnCheck(String cardNumber){ int sum=0; for (int i=cardNumber.length()-1; i>=0; i-=2){ sum+=Integer.parseInt(cardNumber.substring(i, i+1)); if (i>0){ int d=2*Integer.parseInt(cardNumber.substring(i-1, i)); if (d>9) d-=9; sum+=d; } } return sum%10==0; }
Thursday, 17 November 2011
Credit Card Validation --- Luhn Check
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment