CNPJValidator class

A validator that ensures a given string is a valid Brazilian CNPJ.

The CNPJValidator checks whether the provided value follows the Brazilian CNPJ format, which consists of exactly 14 digits (without special characters) or formatted as XX.XXX.XXX/XXXX-XX.

It also verifies:

  • The CNPJ is not a repeated sequence (e.g., "00000000000000").
  • The two check digits are correctly calculated.

Validation Modes

  • ValidationMode.formatted → Expects the CNPJ in the formatted pattern: "XX.XXX.XXX/XXXX-XX"
  • ValidationMode.unformatted (default) → Expects only digits: "XXXXXXXXXXXXXX"

Example

final validator = CNPJValidator(message: 'Invalid CNPJ');

print(validator.validate('12.345.678/0001-95')); // null (valid)
print(validator.validate('12345678000195'));     // null (valid)
print(validator.validate('00.000.000/0000-00')); // 'Invalid CNPJ' (invalid)
print(validator.validate('invalid-cnpj'));       // 'Invalid CNPJ' (invalid)
print(validator.validate('11111111111111'));     // 'Invalid CNPJ' (invalid)

Behavior

  • Ensures the CNPJ format matches the expected pattern.
  • Removes non-digit characters when ValidationMode.unformatted is used.
  • Rejects values where all characters are the same (e.g., "00000000000000").
  • Validates check digits using the official CNPJ verification algorithm.
Inheritance

Constructors

CNPJValidator.new({required String message, ValidationMode mode = ValidationMode.unformatted})
Creates a CNPJValidator with a custom message for validation failures.

Properties

hashCode int
The hash code for this object.
no setterinherited
message String
The error message to be returned when validation fails.
finalinherited
mode ValidationMode
Defines whether the CNPJ should be validated as formatted (XX.XXX.XXX/XXXX-XX) or unformatted (XXXXXXXXXXXXXX).
final
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
toString() String
A string representation of this object.
inherited
validate(covariant String value) String?
Validates the provided value.
override

Operators

operator ==(Object other) bool
The equality operator.
inherited