lacus / cnpj-val
Utility to validate CNPJ (Brazilian Business Tax ID)
Requires
- php: ^8.2
- lacus/cnpj-dv: ^1.1
- lacus/utils: ^1.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.94
- pestphp/pest: ^3.8
- phpstan/phpstan: ^2.1
README
π Full support for the new alphanumeric CNPJ format.
A PHP utility to validate CNPJ (Brazilian Business Tax ID) values.
PHP Support
| Passing β | Passing β | Passing β | Passing β |
Features
- β Alphanumeric CNPJ: Validates 14-character CNPJ in numeric or alphanumeric format
- β
Flexible input: Accepts
stringorlist<string>; array elements are concatenated in order - β
Format agnostic: Strips non-alphanumeric characters (or non-digits when
typeisnumeric) and optionally uppercases letters - β
Optional case sensitivity: When
caseSensitiveisfalse, lowercase letters are accepted for alphanumeric CNPJ - β
Per-call override model: Instance defaults can be overridden for one
isValid()call only - β
Typed option validation: Dedicated
TypeError/Exceptionsubclasses for invalid option or input usage - β
Dual API style: Object-oriented (
CnpjValidator) and functional (cnpj_val())
Installation
# using Composer
$ composer require lacus/cnpj-val
Import
<?php use Lacus\BrUtils\Cnpj\CnpjValidator; use Lacus\BrUtils\Cnpj\CnpjValidatorOptions; use Lacus\BrUtils\Cnpj\Enums\CnpjValidationType; use function Lacus\BrUtils\Cnpj\cnpj_val;
Quick start
<?php use Lacus\BrUtils\Cnpj\CnpjValidator; $validator = new CnpjValidator(); $validator->isValid('98765432000198'); // true $validator->isValid('98.765.432/0001-98'); // true $validator->isValid('98765432000199'); // false $validator->isValid('1QB5UKALPYFP59'); // true (alphanumeric) $validator->isValid('1QB5UKALpyfp59'); // false (default is case-sensitive) $validator->isValid('1QB5UKALpyfp59', caseSensitive: false); // true $validator->isValid('96206256120884'); // true (numeric) $validator->isValid('1QB5UKALPYFP59', type: CnpjValidationType::Numeric); // false
Functional helper:
cnpj_val('98765432000198'); // true cnpj_val('98.765.432/0001-98'); // true cnpj_val('98765432000199'); // false
Usage
The main entry points are the class CnpjValidator, the options value object CnpjValidatorOptions, the enum CnpjValidationType, and the helper cnpj_val().
CnpjValidator
-
__construct:new CnpjValidator(?CnpjValidatorOptions $options = null, $type = null, $caseSensitive = null)If
$optionsis aCnpjValidatorOptionsinstance, that same instance is stored internally (mutations later affect futureisValid()calls with no per-call override). Otherwise, a new options object is built from named values. -
getOptions(): Returns the internalCnpjValidatorOptionsinstance. -
isValid:isValid(string|list<string> $cnpjInput, ?CnpjValidatorOptions $options = null, $type = null, $caseSensitive = null): boolPer-call options are merged over instance defaults only for that call. Returns
truewhen the sanitized input has exactly 14 characters, the last two are digits, and check digits match (CnpjCheckDigitsfromlacus/cnpj-dv). Otherwise returnsfalse(invalid CNPJ, wrong length, ineligible base/branch, etc.) without throwing.If the input is not a
stringor alistof strings,CnpjValidatorInputTypeErroris thrown.
<?php use Lacus\BrUtils\Cnpj\CnpjValidator; use Lacus\BrUtils\Cnpj\Enums\CnpjValidationType; $validator = new CnpjValidator(type: CnpjValidationType::Numeric); $validator->isValid('98.765.432/0001-98'); // true $validator->isValid('1QB5UKALPYFP59'); // false (letters stripped β length β 14) $validator->isValid('1QB5UKALpyfp59', type: CnpjValidationType::Alphanumeric, caseSensitive: false); // true
Default options on the instance; per-call overrides:
$validator = new CnpjValidator(caseSensitive: false); $validator->isValid('1qb5ukalpyfp59'); // true (instance defaults) $validator->isValid('1qb5ukalpyfp59', caseSensitive: true); // this call only: false $validator->isValid('1qb5ukalpyfp59'); // true again
CnpjValidatorOptions
Holds validator settings (type, caseSensitive). Construct with named parameters and optional overrides (list of arrays and/or other CnpjValidatorOptions instances, merged in order). Exposes properties via magic __get / __set.
getAll(): Returns a shallow array snapshot of all options.set(...): Updates multiple fields at once; returns$this.
CnpjValidationType
Backed enum for the type option:
CnpjValidationType::Alphanumeric("alphanumeric") β default; keeps0β9andAβZafter sanitization.CnpjValidationType::Numeric("numeric") β legacy numeric-only CNPJ; strips everything except0β9.
Helper methods:
CnpjValidationType::values(): list<string>toSequenceType(): SequenceType(fromlacus/utils)
String literals 'alphanumeric' and 'numeric' are also accepted wherever type is documented.
Functional helper
cnpj_val() runs the validation on a CnpjValidator instance with the same arguments passed to the function. Use named arguments for options:
cnpj_val('98765432000198'); // true cnpj_val('1QB5UKALpyfp59', caseSensitive: false); // true cnpj_val('1QB5UKALPYFP59', type: CnpjValidationType::Numeric); // false
To pass a full options object as the second argument: cnpj_val($cnpj, new CnpjValidatorOptions(type: CnpjValidationType::Numeric)).
Input formats
String: Raw digits and/or letters, or formatted CNPJ (e.g. 98.765.432/0001-98, 1Q.B5U.KAL/PYFP-59). Characters are stripped according to type; when caseSensitive is false, letters are uppercased before alphanumeric validation.
Array of strings: Each element must be a string; values are concatenated (e.g. per digit, grouped segments, or mixed with punctuation). Non-string elements throw CnpjValidatorInputTypeError.
Validation options
| Parameter | Type | Default | Description |
|---|---|---|---|
type |
CnpjValidationType|'alphanumeric'|'numeric'|null |
CnpjValidationType::Alphanumeric |
Character set after sanitization: alphanumeric (0β9, AβZ) or numeric-only (0β9) |
caseSensitive |
?bool |
true |
When false, lowercase letters are uppercased before alphanumeric validation |
Invalid CNPJ (wrong length after sanitization, invalid check digits, ineligible base/branch 00000000 / 0000, repeated digits, non-numeric verifier digits) returns false β no exception is thrown for validation failure.
Errors & exceptions
This package uses TypeError for invalid option/input types and Exception for invalid option values. Validation failures return false.
- Wrong input type (not
stringorlist<string>):CnpjValidatorInputTypeErrorβ extendsCnpjValidatorTypeError(extends PHPTypeError). - Invalid option types when constructing or merging options:
CnpjValidatorOptionsTypeError. - Invalid
typevalue (notalphanumeric/numeric):CnpjValidatorOptionTypeInvalidExceptionβ extendsCnpjValidatorException.
<?php use Lacus\BrUtils\Cnpj\CnpjValidator; use Lacus\BrUtils\Cnpj\Exceptions\CnpjValidatorInputTypeError; use Lacus\BrUtils\Cnpj\Exceptions\CnpjValidatorOptionTypeInvalidException; try { (new CnpjValidator())->isValid(12345678000198); } catch (CnpjValidatorInputTypeError $e) { echo $e->getMessage(); } try { new CnpjValidator(type: 'invalid'); } catch (CnpjValidatorOptionTypeInvalidException $e) { echo $e->getMessage(); }
Other available resources
CnpjValidatorOptions::CNPJ_LENGTH:14β standard CNPJ length after sanitization.
Contribution & Support
We welcome contributions! Please see our Contributing Guidelines for details. If you find this project helpful, please consider:
- β Starring the repository
- π€ Contributing to the codebase
- π‘ Suggesting new features
- π Reporting bugs
License
This project is licensed under the MIT License β see the LICENSE file for details.
Changelog
See CHANGELOG for a list of changes and version history.
Made with β€οΈ by Lacus Solutions