Php validar Rut (Documento de identidad chileno)


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. function rutValido( $rut ){
  2. if( empty( $rut ) ) return false;
  3.  
  4. if (!preg_match("/(\d{7,8})-([\dK])/", strtoupper($rut), $aMatch)) {
  5. return false;
  6. }
  7. $sRutBase = substr(strrev($aMatch[1]) , 0, 8 );
  8. $sCodigoVerificador = $aMatch[2];
  9. $iCont = 2;
  10. $iSuma = 0;
  11. for ($i = 0;$i<strlen($sRutBase);$i++) {
  12. if ($iCont>7) {
  13. $iCont = 2;
  14. }
  15. $iSuma+= ($sRutBase{$i}) *$iCont;
  16. $iCont++;
  17. }
  18. $iDigito = 11-($iSuma%11);
  19. $sCaracter = substr("-123456789K0", $iDigito, 1);
  20. return ($sCaracter == $sCodigoVerificador);
  21. }
  22. echo rutValido('12159116-2') ? 1 : 0; #Out 1
  23. echo rutValido('54545454545') ? 1 : 0; #Out 0

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.