validator
validator copied to clipboard
Validate if only one out of two fields is present
Version: v9
Hey there,
Is it possible to validate the following:
type User struct {
PhoneNumber string
Email string
}
Given this structure, always only one of these fields should be present, either Email or Phone number. Both shouldn't be present together and both shouldn't be absent either. I tried 'required_without', but here it allows both to be present.
excluded_with
does what you're looking for
var req struct {
PhoneNumber string `validate:"excluded_with=Email"`
Email string `validate:"excluded_with=PhoneNumber"`
}
i have this definition:
type RecoverPasswordRequest struct {
Username string json:"username" validate:"excluded_with=FiscalCode"
FiscalCode string json:"fiscal_code" validate:"excluded_with=Username"
}
with this request: { "pippo": "[email protected]", "pluto": "RWMSSO77M52H829L" }
i have no error on validation, what I am wrong? thanks
thanks @BrianLeishman I've tried your solution, and this works perfect for me
type LoginUserDto struct {
Email string `json:"email,omitempty" validate:"excluded_with=username,email"`
Username string `json:"username,omitempty" validate:"excluded_with=email"`
Password string `json:"password" validate:"required"`
}
@ashalfarhan this doesn't work for struct I've opened https://github.com/go-playground/validator/issues/906
@ashalfarhan this doesn't work for struct I've opened #906
I've tried this way actually
type LoginUserFields struct {
Email string `json:"email" validate:"required_without=Username,omitempty,email"`
Username string `json:"username" validate:"required_without=Email,omitempty"`
Password string `json:"password" validate:"required"`
}
@ashalfarhan yes, but it doesn't work if the fields are structs