英文:
Need to validate two fields in go-playground/validator/v10
问题
需要检查至少一个字段应该存在,即电子邮件和电话至少一个是必需的。
目前我有自定义验证器。
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
}
但是它会引发恐慌。
用户是gorm模型。
在这种情况下,如何检查这两个字段?
英文:
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
答案1
得分: 1
在validator
中有很多条件性的required
标签。
在你的情况下,你可能想要使用required_without_all
+ omitempty
。
required_without_all
- 如果列表中的所有字段都为空,则使字段为必需。
omitempty
- 允许字段为空。
请记住,required
标签必须在omitempty
之前。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论