Skip to content

Instantly share code, notes, and snippets.

@andersonbosa
Created April 3, 2025 20:58
Show Gist options
  • Save andersonbosa/78142ebdd733970f201ad4e449d8c0db to your computer and use it in GitHub Desktop.
Save andersonbosa/78142ebdd733970f201ad4e449d8c0db to your computer and use it in GitHub Desktop.
package main
import (
"errors"
"fmt"
"regexp"
)
type ValidatorFunc func(value string) (bool, error)
type ValidationRules struct {
AllowList []ValidatorFunc
DenyList []ValidatorFunc
}
func (vr *ValidationRules) Validate(value string) (bool, error) {
for _, deny := range vr.DenyList {
if valid, err := deny(value); !valid {
return false, err
}
}
for _, allow := range vr.AllowList {
if valid, _ := allow(value); valid {
return true, nil
}
}
return false, errors.New("valor não permitido")
}
func validateIDFormat(value string) (bool, error) {
match, _ := regexp.MatchString(`^\d{1,10}$`, value)
if !match {
return false, errors.New("ID inválido: deve conter apenas números e ter no máximo 10 dígitos")
}
return true, nil
}
func denySpecialChars(value string) (bool, error) {
match, _ := regexp.MatchString(`[^a-zA-Z0-9]`, value)
if match {
return false, errors.New("valor contém caracteres especiais não permitidos")
}
return true, nil
}
// Validadores para AmountMoney
func validateAmountFormat(value string) (bool, error) {
match, _ := regexp.MatchString(`^\d+(\.\d{1,2})?$`, value)
if !match {
return false, errors.New("quantia inválida: deve ser um número com até duas casas decimais")
}
return true, nil
}
func denyNegativeAmount(value string) (bool, error) {
if value[0] == '-' {
return false, errors.New("quantia não pode ser negativa")
}
return true, nil
}
func main() {
idRules := ValidationRules{
AllowList: []ValidatorFunc{validateIDFormat},
DenyList: []ValidatorFunc{denySpecialChars},
}
amountRules := ValidationRules{
AllowList: []ValidatorFunc{validateAmountFormat},
DenyList: []ValidatorFunc{denyNegativeAmount},
}
tests := map[string]string{
"Valid ID": "123456",
"Invalid ID": "123@456",
"Valid Amount": "100.50",
"Invalid Amount": "-50.00",
}
for testName, value := range tests {
var rules *ValidationRules
if testName == "Valid ID" || testName == "Invalid ID" {
rules = &idRules
} else {
rules = &amountRules
}
valid, err := rules.Validate(value)
fmt.Printf("%s (%s): Valid=%v, Error=%v\n", testName, value, valid, err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment