我正在测试这个 required_with 和 len。
package main
import "fmt"
import "github.com/go-playground/validator/v10"
type NomineeChangeInfo struct {
Name string `json:"name" validate:"required_with=Dob,max=40"`
Dob string `json:"dob" validate:"required_with=Name,len=10"`
}
func main() {
fmt.Println("Hello, Go in CodeSandbox!")
validate := validator.New()
// Define a form with Email provided but Username missing
formWithEmail := NomineeChangeInfo{
Dob:"",
Name:"",
}
// Validate the form
err := validate.Struct(formWithEmail)
if err != nil {
fmt.Println("Validation error:", err)
} else {
fmt.Println("Validation successful")
}
}
在上面的示例中,Name 和 DOB 都不存在,因此它应该不会抛出任何错误。如果我们看到 DOB 的标签顺序,首先我们检查 required_with 然后只有我们正在做 len。
错误为
Error:Field validation for 'Dob' failed on the 'len' tag
。
如果我理解正确,那么 pkg 会抛出一个错误,因为 https://pkg.go.dev/github.com/go-playground/validator/v10#hdr-Length
即使有了这个描述,我也不认为它适用于其他条件语句(如
len
),看起来当我测试它时它现在应该抛出,但它抛出了。
https://pkg.go.dev/github.com/go-playground/validator/v10#hdr-Required_With
这说的是
仅当任何其他指定字段存在时,验证字段才必须存在且不为空。对于字符串,确保值不是“”。对于切片、映射、指针、接口、通道和函数,确保值不为零。对于结构,确保值不是零值。