go-playground / validator

:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
MIT License
16.87k stars 1.32k forks source link

how to settting email field when after required_if tag? #886

Open wyzwhp opened 2 years ago

wyzwhp commented 2 years ago

Package version eg. v9, v10:

V10

Issue, Question or Enhancement:

In this struct ,validator check email format error, how to settting email's validate?

Code sample, to showcase or reproduce:

for example ,in this Struct

type AccountRegisterParams struct {
    RegisterType string `json:"register_type" form:"register_type"  validate:"required,oneof=username email mobile"` 
    UserName     string `json:"user_name" form:"user_name"  validate:"required,max=50"`                              
    Email        string `json:"email" form:"email" validate:"required_if=register_type email,email,max=50"`          
    Mobile       string `json:"mobile" form:"mobile" validate:"required_if=register_type mobile,max=50"`             
    Password     string `json:"password" form:"password"  validate:"required,min=8,max=20"`                          
    Captcha      string `json:"captcha" form:"captcha" validate:"required,max=6"`                                    
    ClientId     string `json:"client_id" form:"client_id" validate:"required"`                               
}
zemzale commented 2 years ago

I think the problem here would the fact that you are not using the correct name of the field for required_if to work. It should match the exact name of the field you validating against. In this case it would be

    RegisterType string `json:"register_type" form:"register_type"  validate:"required,oneof=username email mobile"` 
    UserName     string `json:"user_name" form:"user_name"  validate:"required,max=50"`                              
    Email        string `json:"email" form:"email" validate:"required_if=RegisterType email,email,max=50"`          
    Mobile       string `json:"mobile" form:"mobile" validate:"required_if=RegisterType mobile,max=50"`             
    Password     string `json:"password" form:"password"  validate:"required,min=8,max=20"`                          
    Captcha      string `json:"captcha" form:"captcha" validate:"required,max=6"`                                    
    ClientId     string `json:"client_id" form:"client_id" validate:"required"`                               
}

See the difference here is instead of required_if=register_type email it's required_if=RegisterType email

wyzwhp commented 2 years ago

thanks

wyzwhp commented 2 years ago

thanks