Question:
I have a form and I need to block the CPF entry in this one.
<div id="document" class="form-group">
<input type="text" name="document" class="form-control" placeholder="CNPJ da Empresa" />
<label for="document" class="text-danger">Informe um documento válido</label>
<i class="fa fa-2x form-control-feedback"></i>
</div>
from this form, the information is sent to the registration page which you receive as follows:
header("Access-Control-Allow-Origin: *");
$document = addslashes($_POST["document"]);
My problem is: how to block the CPF entry if possible in the form yet?
I tried to do a strlen to check if the size is greater than 11 (number of CPF numbers), but it always returns 0 (zero).
if (strlen(document) > 11) {
$document = addslashes($_POST["document"]);
}
help please
graciously
Answer:
PHP Library for Validation
A good library to do this validation is Respect\Validation
.
Javascript validation
Another option is to use the function generated by the Gerador de CNPJ
website. Only it's in javascript
http://www.geradorcnpj.com/javascript-validar-cnpj.htm
function validarCNPJ(cnpj) {
cnpj = cnpj.replace(/[^\d]+/g,'');
if(cnpj == '') return false;
if (cnpj.length != 14)
return false;
// Elimina CNPJs invalidos conhecidos
if (cnpj == "00000000000000" ||
cnpj == "11111111111111" ||
cnpj == "22222222222222" ||
cnpj == "33333333333333" ||
cnpj == "44444444444444" ||
cnpj == "55555555555555" ||
cnpj == "66666666666666" ||
cnpj == "77777777777777" ||
cnpj == "88888888888888" ||
cnpj == "99999999999999")
return false;
// Valida DVs
tamanho = cnpj.length - 2
numeros = cnpj.substring(0,tamanho);
digitos = cnpj.substring(tamanho);
soma = 0;
pos = tamanho - 7;
for (i = tamanho; i >= 1; i--) {
soma += numeros.charAt(tamanho - i) * pos--;
if (pos < 2)
pos = 9;
}
resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
if (resultado != digitos.charAt(0))
return false;
tamanho = tamanho + 1;
numeros = cnpj.substring(0,tamanho);
soma = 0;
pos = tamanho - 7;
for (i = tamanho; i >= 1; i--) {
soma += numeros.charAt(tamanho - i) * pos--;
if (pos < 2)
pos = 9;
}
resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
if (resultado != digitos.charAt(1))
return false;
return true;
}
You might want to refactor this javascript
there if you have a better sense of javascript.
PHP validation
Here is a function to validate cnpj
in PHP:
function validar_cnpj($cnpj)
{
$cnpj = preg_replace('/[^0-9]/', '', (string) $cnpj);
// Valida tamanho
if (strlen($cnpj) != 14)
return false;
// Valida primeiro dígito verificador
for ($i = 0, $j = 5, $soma = 0; $i < 12; $i++)
{
$soma += $cnpj{$i} * $j;
$j = ($j == 2) ? 9 : $j - 1;
}
$resto = $soma % 11;
if ($cnpj{12} != ($resto < 2 ? 0 : 11 - $resto))
return false;
// Valida segundo dígito verificador
for ($i = 0, $j = 6, $soma = 0; $i < 13; $i++)
{
$soma += $cnpj{$i} * $j;
$j = ($j == 2) ? 9 : $j - 1;
}
$resto = $soma % 11;
return $cnpj{13} == ($resto < 2 ? 0 : 11 - $resto);
}
Source: https://gist.github.com/guisehn/3276302