Pascal Klein - 1 year ago 103
PHP Question

# PHP validate German Tax Id (Steueridentifikationsnummer)

The German Tax Id (Steueridentifikationsnummer) has the following properties:

1. It has 11 digits

2. First digit cannot be 0

3. In the first ten digits, one number occurs exactly twice, on number exactly zero times, and the other 8 number occure once

4. The last digit is a checksum Example Code for Checksum

The third bulletpoint is a little difficult for me to solve in an elegant way. I already have the code for the other three bulletpoints, but would love to get input for the last one, so that this could be a small little reference for other people.

``````# validate tax number
\$taxNumber = \$_POST['taxNumber'];
echo preg_replace("/[^0-9]/", "", \$taxNumber);

if (strlen(\$taxNumber != 11)) {
# 11 digits
\$taxNumberValid = false;
} else if (\$taxNumber[0] == "0") {
# first digit != 0
\$taxNumberValid = false;
} else {
# one digit two times, one digit zero times

# checksum
\$numbers = str_split(\$taxNumber);
\$sum = 0;
\$product = 10;
for (\$i = 0; \$i <= 9; \$i++) {
\$sum = (\$numbers[\$i] + \$product) % 10;
if (\$sum == 0) {
\$sum = 10;
}
\$product = (\$sum * 2) % 11;
}
\$checksum = 11 - \$product;
if (\$checksum == 10) {
\$checksum = 0;
}

if (\$taxNumber[10] != \$checksum) {
\$taxNumberValid = false;
}
}
``````

This code solves the problem:

``````// remove whitespaces, slashes & other unnecessary characters
\$taxNumber = preg_replace("/[^0-9]/", "", \$taxNumber);

// by default the taxnumber is correct
\$taxNumberValid = true;

// taxnumber has to have exactly 11 digits
if (strlen(\$taxNumber) != 11) {
\$taxNumberValid = false;
}

// first digit cannot be 0
if (\$taxNumber[0] == "0") {
\$taxNumberValid = false;
}

/*
make sure that within the first ten digits:
1.) one digit appears exactly twice or thrice
2.) one or two digits appear zero times
3.) and oll other digits appear exactly once once
*/
\$digits = str_split(\$taxNumber);
\$first10Digits = \$digits;
array_pop(\$first10Digits);
\$countDigits = array_count_values (\$first10Digits);
if (count(\$countDigits) != 9 && count(\$countDigits) != 8) {
\$taxNumberValid = false;
}

// last check: 11th digit has to be the correct checkums
// see http://de.wikipedia.org/wiki/Steueridentifikationsnummer#Aufbau_der_Identifikationsnummer
\$sum = 0;
\$product = 10;
for(\$i = 0; \$i <= 9; \$i++) {
\$sum = (\$digits[\$i] + \$product) % 10;
if (\$sum == 0) {
\$sum = 10;
}
\$product = (\$sum * 2) % 11;
}
\$checksum = 11 - \$product;
if (\$checksum == 10) {
\$checksum = 0;
}
if (\$taxNumber[10] != \$checksum) {
\$taxNumberValid = false;
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download