lacus/cnpj-val
Composer 安装命令:
composer require lacus/cnpj-val
包简介
Utility to validate CNPJ (Brazilian Business Tax ID)
README 文档
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
lacus/cnpj-val 适用场景与选型建议
lacus/cnpj-val 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 818 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 09 月 03 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「validator」 「validate」 「valid」 「cnpj」 「br」 「validador」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 lacus/cnpj-val 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 lacus/cnpj-val 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 lacus/cnpj-val 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Cascade attribute for Symfony Validator, reimplementing the Valid constraint in a more flexible and understandable way
Runn Me! Validation and Sanitization Library
Extension for Opis JSON Schema
Supercharged text field validation.
Simple, elegant, stand-alone validation library with NO dependencies
Simple minimal but useful set of utils (properties, strings, datetimes, etc.)
统计信息
- 总下载量: 818
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 24
- 依赖项目数: 1
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-09-03