| 123456789101112131415161718192021222324252627282930313233 |
- package models
- import (
- "regexp"
- "github.com/go-playground/validator/v10"
- "gorm.io/gorm"
- )
- // User struct with validation tags
- type User struct {
- gorm.Model
- FirstName string `json:"first_name" validate:"required,min=2,max=40,uppercase"`
- LastName string `json:"last_name" validate:"required,min=2,max=40,uppercase"`
- Sex string `json:"sex" validate:"required,oneof=H M"`
- BirthDate string `json:"birth_date" validate:"required,birthdate"` //dd-mm-yyyy
- }
- // Validate validates the User struct
- func (u *User) Validate() error {
- validate := validator.New()
- // Custom validation for BirthDate
- validate.RegisterValidation("birthdate", func(fl validator.FieldLevel) bool {
- re := regexp.MustCompile(`^(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[0-2])-\d{4}$`)
- return re.MatchString(fl.Field().String())
- })
- // Custom validation for Uppercase
- validate.RegisterValidation("uppercase", func(fl validator.FieldLevel) bool {
- re := regexp.MustCompile(`^[A-Z]+$`) // Permite solo letras mayúsculas
- return re.MatchString(fl.Field().String())
- })
- return validate.Struct(u)
- }
|