需要在go-playground/validator/v10中验证两个字段。

huangapple go评论80阅读模式
英文:

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.

Example

huangapple
  • 本文由 发表于 2023年1月21日 21:20:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75193648.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定