01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */
17: package org.apache.cocoon.woody.datatype.validationruleimpl;
18:
19: import org.apache.cocoon.woody.datatype.ValidationError;
20: import org.apache.cocoon.woody.util.I18nMessage;
21: import org.apache.cocoon.woody.Constants;
22: import org.outerj.expression.ExpressionContext;
23:
24: /**
25: * Performs the so called "mod 10" algorithm to check the validity of credit card numbers
26: * such as VISA.
27: *
28: * <p>In addition to this, the credit card number can be further validated by its length
29: * and prefix, but those properties are depended on the credit card type and such validation
30: * is not performed by this validation rule.
31: *
32: * @version $Id: Mod10ValidationRule.java 433543 2006-08-22 06:22:54Z crossley $
33: */
34: public class Mod10ValidationRule extends AbstractValidationRule {
35: public ValidationError validate(Object value,
36: ExpressionContext expressionContext) {
37: String numberToCheck = (String) value;
38: int nulOffset = '0';
39: int sum = 0;
40: for (int i = 1; i <= numberToCheck.length(); i++) {
41: int currentDigit = numberToCheck.charAt(numberToCheck
42: .length()
43: - i)
44: - nulOffset;
45: if ((i % 2) == 0) {
46: currentDigit *= 2;
47: currentDigit = currentDigit > 9 ? currentDigit - 9
48: : currentDigit;
49: sum += currentDigit;
50: } else {
51: sum += currentDigit;
52: }
53: }
54: if (!((sum % 10) == 0))
55: return hasFailMessage() ? getFailMessage()
56: : new ValidationError(new I18nMessage(
57: "validation.mod10",
58: Constants.I18N_CATALOGUE));
59: else
60: return null;
61: }
62:
63: public boolean supportsType(Class clazz, boolean arrayType) {
64: return String.class.isAssignableFrom(clazz) && !arrayType;
65: }
66: }
|