Skip to content

Instantly share code, notes, and snippets.

@britter
Created May 5, 2016 11:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save britter/ff959c42cab142a828247ce0673f6215 to your computer and use it in GitHub Desktop.
Save britter/ff959c42cab142a828247ce0673f6215 to your computer and use it in GitHub Desktop.
Apache Commons Validator CheckDigit implementation for validating German identity card ("Personalausweis") numbers
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines.checkdigit;
public class PersonalausweisCheckDigit extends ModulusCheckDigit {
private static final int UPPER_LETTER_ASCII_OFFSET = 65;
public PersonalausweisCheckDigit() {
super(10);
}
@Override
protected int toInt(final char character, final int leftPos, final int rightPos) throws CheckDigitException {
if (Character.isLetter(character)) {
return toAlphabetPosition(character) + 10;
}
return super.toInt(character, leftPos, rightPos);
}
private static int toAlphabetPosition(final char character) {
return (int) Character.toUpperCase(character) - UPPER_LETTER_ASCII_OFFSET;
}
@Override
protected int weightedValue(final int charValue, final int leftPos, final int rightPos) throws CheckDigitException {
return charValue * getFactor(leftPos);
}
private int getFactor(final int leftPos) {
if (leftPos % 3 == 0) {
return 1;
} else if (leftPos + 1 % 3 == 0) {
return 3;
} else {
return 7;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment