0%

go validator 值为 0 required 验证

错误示范

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main

import (
"fmt"
"github.com/go-playground/validator/v10"
)

type Person struct {
Name string `validate:"required"`
State int `validate:"required,oneof=0 1"`
}

func main() {
validate := validator.New()

p := Person{
Name: "abcc",
State: 0,
}
err := validate.Struct(p)

// Key: 'Person.State' Error:Field validation for 'State' failed on the 'required' tag
fmt.Println(err)
}

在这个例子中,虽然我们的 State 字段传入了值,但是验证却不通过。

正确示范

在使用 go-playground/validator/v10 验证一些空值的时候,需要使用指针类型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package main

import (
"fmt"
"github.com/go-playground/validator/v10"
)

type Person struct {
Name string `validate:"required"`
// 使用指针类型
State *int `validate:"required,oneof=0 1"`
}

func main() {
validate := validator.New()

state := 0

p := Person{
Name: "abcc",
State: &state, // 传入指针
}
err := validate.Struct(p)

// <nil>
fmt.Println(err)
}