validator icon indicating copy to clipboard operation
validator copied to clipboard

Validate if only one out of two fields is present

Open Gunakk opened this issue 3 years ago • 6 comments

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.

Gunakk avatar May 03 '21 12:05 Gunakk

excluded_with does what you're looking for

var req struct {
	PhoneNumber string `validate:"excluded_with=Email"`
	Email       string `validate:"excluded_with=PhoneNumber"`
}

BrianLeishman avatar May 05 '21 19:05 BrianLeishman

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

andreaneri avatar May 11 '21 09:05 andreaneri

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 avatar Jan 23 '22 08:01 ashalfarhan

@ashalfarhan this doesn't work for struct I've opened https://github.com/go-playground/validator/issues/906

petitout avatar Feb 28 '22 23:02 petitout

@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 avatar Mar 01 '22 02:03 ashalfarhan

@ashalfarhan yes, but it doesn't work if the fields are structs

petitout avatar Mar 01 '22 14:03 petitout