lacus/cnpj-val

Utility to validate CNPJ (Brazilian Business Tax ID)

Maintainers

Package info

github.com/LacusSolutions/br-utils-php_cnpj-val

Homepage

Issues

pkg:composer/lacus/cnpj-val

Statistics

Installs: 269

Dependents: 2

Suggesters: 0

Stars: 0

2.0.0 2026-05-23 09:15 UTC

This package is auto-updated.

Last update: 2026-05-23 15:51:27 UTC


README

cnpj-val for PHP

Packagist Version Packagist Downloads PHP Version Test Status Last Update Date Project License

πŸš€ Full support for the new alphanumeric CNPJ format.

🌎 Acessar documentaΓ§Γ£o em portuguΓͺs

A PHP utility to validate CNPJ (Brazilian Business Tax ID) values.

PHP Support

PHP 8.2 PHP 8.3 PHP 8.4 PHP 8.5
Passing βœ” Passing βœ” Passing βœ” Passing βœ”

Features

  • βœ… Alphanumeric CNPJ: Validates 14-character CNPJ in numeric or alphanumeric format
  • βœ… Flexible input: Accepts string or list<string>; array elements are concatenated in order
  • βœ… Format agnostic: Strips non-alphanumeric characters (or non-digits when type is numeric) and optionally uppercases letters
  • βœ… Optional case sensitivity: When caseSensitive is false, 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 / Exception subclasses 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 $options is a CnpjValidatorOptions instance, that same instance is stored internally (mutations later affect future isValid() calls with no per-call override). Otherwise, a new options object is built from named values.

  • getOptions(): Returns the internal CnpjValidatorOptions instance.

  • isValid: isValid(string|list<string> $cnpjInput, ?CnpjValidatorOptions $options = null, $type = null, $caseSensitive = null): bool

    Per-call options are merged over instance defaults only for that call. Returns true when the sanitized input has exactly 14 characters, the last two are digits, and check digits match (CnpjCheckDigits from lacus/cnpj-dv). Otherwise returns false (invalid CNPJ, wrong length, ineligible base/branch, etc.) without throwing.

    If the input is not a string or a list of strings, CnpjValidatorInputTypeError is 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; keeps 0–9 and A–Z after sanitization.
  • CnpjValidationType::Numeric ("numeric") β€” legacy numeric-only CNPJ; strips everything except 0–9.

Helper methods:

  • CnpjValidationType::values(): list<string>
  • toSequenceType(): SequenceType (from lacus/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 string or list<string>): CnpjValidatorInputTypeError β€” extends CnpjValidatorTypeError (extends PHP TypeError).
  • Invalid option types when constructing or merging options: CnpjValidatorOptionsTypeError.
  • Invalid type value (not alphanumeric / numeric): CnpjValidatorOptionTypeInvalidException β€” extends CnpjValidatorException.
<?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:

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