01: /*
02: * $Header: /cvsroot/jvalidate/jvalidate-framework/jvalidate/src/main/java/nl/knowlogy/validation/customvalidators/CreditcardNumberValidator.java,v 1.3 2006/05/25 09:40:01 roberthofstra Exp $
03: * $Revision: 1.3 $
04: * $Date: 2006/05/25 09:40:01 $
05: *
06: *
07: * Created on Oct 6, 2004
08: *
09: * All right reserved(c) 2004, Knowlogy
10: *
11: * Copyright 2004 - 2005 Knowlogy, the Netherlands. All rights reserved.
12: * All Knowlogy brand and product names are trademarks or registered trademarks
13: * of Knowlogy in the Netherlands and other countries.
14: *
15: * No part of this publication may be reproduced, transmitted, stored in a retrieval system,
16: * or translated into any human or computer language, in any form, or by any means, electronic,
17: * mechanical, magnetic, optical, chemical, manual, or otherwise,
18: * without the prior written permission of the copyright owner, Knowlogy.
19: *
20: */
21: package nl.knowlogy.validation.customvalidators;
22:
23: import nl.knowlogy.validation.CustomValidator;
24:
25: /**
26: *
27: * @author Robert
28: */
29: public class CreditcardNumberValidator implements CustomValidator {
30:
31: /* (non-Javadoc)
32: * @see nl.knowlogy.validation.CustomValidator#isValid(java.lang.Object)
33: */
34: public boolean isValid(Object value) {
35: return value != null ? LUHNCheck(value) : true;
36: }
37:
38: // copied from http://www.merriampark.com/anatomycc.htm
39: public boolean LUHNCheck(Object creditcardNumber) {
40: int sum = 0;
41: int digit = 0;
42: int addend = 0;
43: boolean timesTwo = false;
44:
45: for (int i = creditcardNumber.toString().length() - 1; i >= 0; i--) {
46: String num = creditcardNumber.toString()
47: .substring(i, i + 1);
48:
49: try {
50: digit = Integer.parseInt(num);
51: } catch (NumberFormatException nfe) {
52: return false;
53: }
54:
55: if (timesTwo) {
56: addend = digit * 2;
57:
58: if (addend > 9) {
59: addend -= 9;
60: }
61: } else {
62: addend = digit;
63: }
64:
65: sum += addend;
66: timesTwo = !timesTwo;
67: }
68:
69: return ((sum % 10) != 0) ? false : true;
70:
71: }
72:
73: }
|