Created
June 26, 2024 18:55
-
-
Save aritzolaba/21382cd18dc1b52f5f0ab253c8e5d5c5 to your computer and use it in GitHub Desktop.
Validar NIF, CIF y NIE en PHP, actualizado 2024
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function validateIdent( $ident = '' ) { | |
$BASE_REG_EXP = '/((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)/'; | |
$CIF_REG_EXP = '/^[ABCDEFGHJNPQRSUVW]{1}/'; | |
$NIF_REG_EXP = '/(^[0-9]{8}[A-Z]{1}$)/'; | |
$NIE_REG_EXP = '/^[XYZ]{1}/'; | |
$NIS_REG_EXP = '/^[KLM]{1}/'; | |
$NID_STR_SEQ = 'TRWAGMYFPDXBNJZSQVHLCKE'; | |
$ident = mb_strtoupper( $ident ); | |
if ( ! preg_match( $BASE_REG_EXP, $ident ) ) { | |
return false; | |
} | |
$ident_chars = str_split( $ident ); | |
if ( preg_match( $NIF_REG_EXP, $ident ) ) { | |
if ( $ident_chars[8] == substr( $NID_STR_SEQ, | |
substr( $ident, 0, 8 ) % 23, 1 ) ) { | |
return true; | |
} else { | |
return false; | |
} | |
} | |
if ( preg_match( $NIE_REG_EXP, $ident ) ) { | |
if ( $ident_chars[8] == substr( $NID_STR_SEQ, | |
substr( str_replace( [ 'X', 'Y', 'Z' ], [ '0', '1', '2' ], $ident ), | |
0, 8 ) % 23, 1 ) ) { | |
return true; | |
} else { | |
return false; | |
} | |
} | |
$check_sum = $ident_chars[2] + $ident_chars[4] + $ident_chars[6]; | |
for ( $i = 1; $i < 8; $i += 2 ) { | |
$check_sum += intval( substr( ( 2 * $ident_chars[ $i ] ), 0, 1 ) ) + | |
intval( substr( ( 2 * $ident_chars[ $i ] ), 1, 1 ) ); | |
} | |
$check_sum = 10 - intval( substr( $check_sum, strlen( $check_sum ) - 1, 1 ) ); | |
$check_asc = $ident_chars[8] == chr( 64 + $check_sum ); | |
if ( preg_match( $NIS_REG_EXP, $ident ) ) { | |
if ( $check_asc || | |
$ident_chars[8] == substr( $NID_STR_SEQ, substr( $ident, 1, 8 ) % 23, 1 ) ) { | |
return true; | |
} else { | |
return false; | |
} | |
} | |
if ( preg_match( $CIF_REG_EXP, $ident ) ) { | |
if ( $check_asc || | |
$ident_chars[8] == substr( $check_sum, strlen( $check_sum ) - 1, 1 ) ) { | |
return true; | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment