github.com/mundipagg/boleto-api@v0.0.0-20230620145841-3f9ec742599f/models/document.go (about)

     1  package models
     2  
     3  import (
     4  	"regexp"
     5  	"strings"
     6  )
     7  
     8  // Document nó com o tipo de documento e número do documento
     9  type Document struct {
    10  	Type   string `json:"type,omitempty"`
    11  	Number string `json:"number,omitempty"`
    12  }
    13  
    14  // IsCPF diz se o DocumentType é um CPF
    15  func (d Document) IsCPF() bool {
    16  	return strings.ToUpper(d.Type) == "CPF"
    17  }
    18  
    19  // IsCNPJ diz se o DocumentType é um CNPJ
    20  func (d Document) IsCNPJ() bool {
    21  	return strings.ToUpper(d.Type) == "CNPJ"
    22  }
    23  
    24  // ValidateCPF verifica se é um CPF válido
    25  func (d *Document) ValidateCPF() error {
    26  	re := regexp.MustCompile("(\\D+)")
    27  	cpf := re.ReplaceAllString(string(d.Number), "")
    28  	if len(cpf) == 11 {
    29  		d.Number = cpf
    30  		return nil
    31  	}
    32  	return NewErrorResponse("MPDocumentNumber", "CPF inválido")
    33  }
    34  
    35  // ValidateCNPJ verifica se é um CNPJ válido
    36  func (d *Document) ValidateCNPJ() error {
    37  	re := regexp.MustCompile("(\\D+)")
    38  	cnpj := re.ReplaceAllString(string(d.Number), "")
    39  	if len(cnpj) == 14 {
    40  		d.Number = cnpj
    41  		return nil
    42  	}
    43  	return NewErrorResponse("MPDocumentNumber", "CNPJ inválido")
    44  }