Callback para validar CUIT con CodeIgniter PHP

Comparto cómo validar un número de CUIT/CUIL usando un callback de form_validation en un controlador de CodeIgniter:

// Cargo la libreria de validacion de formularios
$this->load->library('form_validation'); 

// Defino las reglas de validacion del formulario
$this->form_validation->set_rules('cuit', 'CUIT', 'xss_clean|required|numeric|callback_valid_cuit');

// ...

if ($this->form_validation->run() != FALSE)
{
    // Todo OK.
}
else
{
    // Error /:
}

Método de callback:

/*
 * Form Validation Callback: Valida un Nro. de CUIT
 */
public function valid_cuit($cuit)
{
    $cuit_array = str_split(str_replace(array(' ', '-'), array(), $cuit));

    if ((count($cuit_array) < 11) OR (count($cuit_array) > 11))
    {
        // Usando lang
        // $this->form_validation->set_message('valid_cuit', $this->lang->line('form_cuit_error'));
        $this->form_validation->set_message('valid_cuit', 'Error al validar el CUIT');

        return FALSE;
    }

    $result  = $cuit_array[0] * 5;
    $result += $cuit_array[1] * 4;
    $result += $cuit_array[2] * 3;
    $result += $cuit_array[3] * 2;
    $result += $cuit_array[4] * 7;
    $result += $cuit_array[5] * 6;
    $result += $cuit_array[6] * 5;
    $result += $cuit_array[7] * 4;
    $result += $cuit_array[8] * 3;
    $result += $cuit_array[9] * 2;

    $div    = intval($result / 11);
    $resto  = $result - ($div * 11);

    if ($resto == 0)
    {
        return ($resto == $cuit_array[10]) ? TRUE : FALSE;
    }
    elseif ($resto == 1)
    {
        if (($cuit_array[10] == 9) AND ($cuit_array[0] == 2) AND ($cuit_array[1] == 3))
        {
            return TRUE;
        }
        elseif (($cuit_array[10] == 4) AND ($cuit_array[0] == 2) AND ($cuit_array[1] == 3))
        {
            return TRUE;
        }
    }
    elseif ($cuit_array[10] == (11 - $resto))
    {
        return TRUE;
    }
    else
    {
        // Usando lang
        // $this->form_validation->set_message('valid_cuit', $this->lang->line('form_cuit_error'));
        $this->form_validation->set_message('valid_cuit', 'Error al validar el CUIT');

        return FALSE;
    }
}

Leave a Reply

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