user.go 1.1 KB

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