Validators for CPF and CNPJ for PHP
MIT License
A PHP library for validating and formatting CPF and CNPJ numbers from Brazil.
You can install this library using Composer. Run the following command in your project directory:
composer require phillarmonic/cpf-cnpj
To validate a CPF number:
use Phillarmonic\CpfCnpj\CPF;
$cpf = new CPF('123.456.789-09');
if ($cpf->isValid()) {
echo "The CPF is valid.";
} else {
echo "The CPF is not valid.";
}
To format a valid CPF number:
use Phillarmonic\CpfCnpj\CPF;
$cpf = new CPF('12345678909');
$formattedCpf = $cpf->format();
if ($formattedCpf !== false) {
echo "Formatted CPF: " . $formattedCpf; // Outputs: 123.456.789-09
} else {
echo "Invalid CPF, unable to format.";
}
To validate a CNPJ number:
use Phillarmonic\CpfCnpj\CNPJ;
$cnpj = new CNPJ('12.345.678/0001-95');
if ($cnpj->isValid()) {
echo "The CNPJ is valid.";
} else {
echo "The CNPJ is not valid.";
}
To format a valid CNPJ number:
use Phillarmonic\CpfCnpj\CNPJ;
$cnpj = new CNPJ('12345678000195');
$formattedCnpj = $cnpj->format();
if ($formattedCnpj !== false) {
echo "Formatted CNPJ: " . $formattedCnpj; // Outputs: 12.345.678/0001-95
} else {
echo "Invalid CNPJ, unable to format.";
}
isValid()
method checks for:
format()
method returns false
if the number is invalid.The library doesn't throw exceptions. Instead, it returns false
or fails silently in case of invalid input. Always check the return value of isValid()
before using the number, and check if format()
returns false
before using the formatted result.
If you'd like to contribute to this project, please submit a pull request on the GitHub repository.
This library is open-sourced software licensed under the MIT license.