Validate a Greek VAT number (ΑΦΜ)
A PHP helper that checks a Greek VAT number (ΑΦΜ) with the official check-digit algorithm, ready to use in forms and WooCommerce.
if ( ! function_exists( 'snipfire_is_valid_afm' ) ) {
/**
* Check a Greek VAT number (ΑΦΜ) with the official check-digit rule.
*
* Accepts spaces and an EL/GR prefix, e.g. "EL 094019245".
* Usage: if ( ! snipfire_is_valid_afm( $value ) ) { ... }
*
* @param string $afm The VAT number to check.
* @return bool True if the number is well formed and the check digit matches.
*/
function snipfire_is_valid_afm( $afm ) {
$afm = preg_replace( '/[\s.\-]/', '', (string) $afm );
$afm = preg_replace( '/^(EL|GR)/i', '', $afm );
if ( ! preg_match( '/^[0-9]{9}$/', $afm ) || '000000000' === $afm ) {
return false;
}
// Multiply the first 8 digits by 256, 128 ... 2 and add them up.
$sum = 0;
for ( $i = 0; $i < 8; $i++ ) {
$sum += (int) $afm[ $i ] * ( 2 ** ( 8 - $i ) );
}
// The remainder mod 11, then mod 10, must equal the 9th digit.
return ( $sum % 11 ) % 10 === (int) $afm[8];
}
}
What it does
A Greek VAT number (ΑΦΜ) has 9 digits, and the last one is a check digit. Checking it catches most typos before an invoice goes out with the wrong number.
This snippet adds the function snipfire_is_valid_afm(). It accepts spaces and an EL or GR prefix, and returns true only if the number has 9 digits and the check digit matches. Call it from your own form or checkout validation.
Good to know
- It checks the format, not whether the ΑΦΜ is registered or active. For that you need AADE's registry service.
- The "Receipt or invoice choice" snippet already includes this check, so you don't need both for that.