1

need to check atleast one of field should be present email, phone atleast one is mandatory

currently I have custom validator

func validateEmailPhone(fl validator.FieldLevel) bool {
    user := fl.Top().Interface().(models.User)
    validate := validator.Validate{}

    if user.Email == "" && user.Phone == "" {
        return false
    }
    if user.Email != "" {
        if err := validate.Var(user.Email, "email"); err != nil {
            return false
        }
    }
    if user.Phone != "" {
        if err := validate.Var(user.Phone, "e164"); err != nil {
            return false
        }
    }
    return true
}

but its panic

the user is gorm model

in this scenario how to check these two fields

dmitryro
  • 3,463
  • 2
  • 20
  • 28
Arul Ranjith
  • 465
  • 1
  • 5
  • 17
  • You should probably use `Parent()` instead of `Top()`. And to avoid panics you should use the *special* "comma ok" form of assignment when doing type assertions, i.e. `u, ok := fl.Parent().Interface().(models.User)`. And if `ok` is `false` then that means that the `Parent` of the field is not `models.User` but instead some other type. You can find out what type it is by simply printing it with the `%T` verb: `fmt.Printf("%T\n", fl.Parent().Interface())`. – mkopriva Jan 21 '23 at 17:19

1 Answers1

1

There are plenty of conditional required tags in validator. In your case, you probably want required_without_all + omitempty.

required_without_all - makes a field required if all fields in the list are empty.

omitempty - simply allows the field to be empty.

Please keep in mind that the required tag must come before omitempty.

Example

Igor Morozov
  • 194
  • 1
  • 6