Validação Número Cartão do Cidadão em PHP

[DEMO]

Esta função verifica se um número de cartão de cidadão é válido:

<?php

function ValidateNumeroDocumentoCC($numeroDocumento)
{
    $numeroDocumento = str_replace(' ','', strtoupper($numeroDocumento));

    $sum = 0;
    $secondDigit = false;

    if(strlen($numeroDocumento) != 12) throw new exception("Tamanho inválido para número de documento.");

    for ($i = strlen($numeroDocumento)-1; $i >= 0; --$i) {
        $valor = GetNumberFromChar($numeroDocumento[$i]);
        if ($secondDigit)
        {
            $valor *= 2;
            if ($valor > 9) $valor -= 9;
        }

        $sum += $valor;
        $secondDigit = !$secondDigit;

    }
    return ($sum % 10) == 0;

}

function GetNumberFromChar($letter) {
        switch($letter) {
            case '0' : return 0;
            case '1' : return 1;
            case '2' : return 2;
            case '3' : return 3;
            case '4' : return 4;
            case '5' : return 5;
            case '6' : return 6;
            case '7' : return 7;
            case '8' : return 8;
            case '9' : return 9;
            case 'A' : return 10;
            case 'B' : return 11;
            case 'C' : return 12;
            case 'D' : return 13;
            case 'E' : return 14;
            case 'F' : return 15;
            case 'G' : return 16;
            case 'H' : return 17;
            case 'I' : return 18;
            case 'J' : return 19;
            case 'K' : return 20;
            case 'L' : return 21;
            case 'M' : return 22;
            case 'N' : return 23;
            case 'O' : return 24;
            case 'P' : return 25;
            case 'Q' : return 26;
            case 'R' : return 27;
            case 'S' : return 28;
            case 'T' : return 29;
            case 'U' : return 30;
            case 'V' : return 31;
            case 'W' : return 32;
            case 'X' : return 33;
            case 'Y' : return 34;
            case 'Z' : return 35;

    }
    throw new exception('Caractere inválido no número de documento: ' . $letter);
}

?>

Basta chamar a função ValidateNumeroDocumentoCC()
[DEMO] ou [Download] demo completo.

Poderei fazer a versão em jquery ou javascript, diga se estiver interessado.


Programação

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>