Skip to content

Cnpj ​

Utility for the Brazilian CNPJ, numeric and alphanumeric (14 characters; the last two are check digits).

csharp
using Gryd.Core.Documents;

API Reference ​

MethodReturnDescription
Normalize(string?)string?Strips ., /, - and spaces, upper-cases; null if it does not match ^[0-9A-Z]{12}[0-9]{2}$
IsValid(string?)boolNormalizes, rejects 14 equal characters, checks both digits
Format(string)stringXX.XXX.XXX/XXXX-DD; throws ArgumentException if the value is not normalized
Mask(string?)string**.***.XXX/****-** (positions 5 to 7), **.***.***/****-** for other text, *** for null/empty

Check digits ​

The value of each character is its ASCII code minus 48 (0-9 → 0-9, A-Z → 17-42). The first digit uses weights 5,4,3,2,9,8,7,6,5,4,3,2, the second 6,5,4,3,2,9,8,7,6,5,4,3,2. With r = sum % 11, the digit is r < 2 ? 0 : 11 - r.

csharp
Cnpj.IsValid("12.abc.345/01de-35");          // true
Cnpj.Normalize("12.abc.345/01de-35");        // "12ABC34501DE35"
Cnpj.Format("12ABC34501DE35");               // "12.ABC.345/01DE-35"
Cnpj.Mask("12ABC34501DE35");                 // "**.***.345/****-**"

SensitiveDataMasker.MaskCnpj delegates to Cnpj.Mask, and SensitiveDataMasker.AutoMask masks any valid CNPJ.

Released under the MIT License.