Skip to content

Instantly share code, notes, and snippets.

@juanmanavarro
Last active August 25, 2017 08:59
Show Gist options
  • Save juanmanavarro/065744c4c25e4d9d01dfda36837aeec9 to your computer and use it in GitHub Desktop.
Save juanmanavarro/065744c4c25e4d9d01dfda36837aeec9 to your computer and use it in GitHub Desktop.
[PHP] Spanish NIF validation - https://github.com/mpijierro/identity
<?php
function validateNif($nif) {
$nifRegEx = '/^[0-9]{8}[A-Z]$/i';
$nieRegEx = '/^[XYZ][0-9]{7}[A-Z]$/i';
$letras = "TRWAGMYFPDXBNJZSQVHLCKE";
if (preg_match($nifRegEx, $nif)) {
return ($letras[(substr($nif, 0, 8) % 23)] == $nif[8]);
} else {
if (preg_match($nieRegEx, $nif)) {
if ($nif[0] == "X") {
$nif[0] = "0";
} else {
if ($nif[0] == "Y") {
$nif[0] = "1";
} else {
if ($nif[0] == "Z") {
$nif[0] = "2";
}
}
}
return ($letras[(substr($nif, 0, 8) % 23)] == $nif[8]);
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment