KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > woody > datatype > validationruleimpl > Mod10ValidationRule


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.apache.cocoon.woody.datatype.validationruleimpl;
17
18 import org.apache.cocoon.woody.datatype.ValidationError;
19 import org.apache.cocoon.woody.util.I18nMessage;
20 import org.apache.cocoon.woody.Constants;
21 import org.outerj.expression.ExpressionContext;
22
23 /**
24  * Performs the so called "mod 10" algorithm to check the validity of credit card numbers
25  * such as VISA.
26  *
27  * <p>In addition to this, the credit card number can be further validated by its length
28  * and prefix, but those properties are depended on the credit card type and such validation
29  * is not performed by this validation rule.
30  *
31  * @version $Id: Mod10ValidationRule.java 30932 2004-07-29 17:35:38Z vgritsenko $
32  */

33 public class Mod10ValidationRule extends AbstractValidationRule {
34     public ValidationError validate(Object JavaDoc value, ExpressionContext expressionContext) {
35         String JavaDoc numberToCheck = (String JavaDoc)value;
36         int nulOffset = '0';
37         int sum = 0;
38         for (int i = 1; i <= numberToCheck.length(); i++) {
39             int currentDigit = numberToCheck.charAt(numberToCheck.length() - i) - nulOffset;
40             if ((i % 2) == 0) {
41                 currentDigit *= 2;
42                 currentDigit = currentDigit > 9 ? currentDigit - 9 : currentDigit;
43                 sum += currentDigit;
44             } else {
45                 sum += currentDigit;
46             }
47         }
48         if(!((sum % 10) == 0))
49             return hasFailMessage() ? getFailMessage() : new ValidationError(new I18nMessage("validation.mod10", Constants.I18N_CATALOGUE));
50         else
51             return null;
52     }
53
54     public boolean supportsType(Class JavaDoc clazz, boolean arrayType) {
55         return String JavaDoc.class.isAssignableFrom(clazz) && !arrayType;
56     }
57 }
58
Popular Tags