如何验证像Java语言的Joi这样的Go对象数据?

时间:2018-12-29 13:03:55

标签: go

我使用Joi在JavaScript中进行对象模式和数据验证。在Golang中,我知道如何进行模式验证,但是如何进行数据验证?

Golang是否有Joi等值产品?我知道Godog,但尚未达到1.0。

1 个答案:

答案 0 :(得分:2)

尝试ozzo验证https://github.com/go-ozzo/ozzo-validation

package main

import (
    "fmt"
    "regexp"

    "github.com/go-ozzo/ozzo-validation"
    "github.com/go-ozzo/ozzo-validation/is"
)

type Address struct {
    Street string
    City   string
    State  string
    Zip    string
}

func (a Address) Validate() error {
    return validation.ValidateStruct(&a,
        // Street cannot be empty, and the length must between 5 and 50
        validation.Field(&a.Street, validation.Required, validation.Length(5, 50)),
        // City cannot be empty, and the length must between 5 and 50
        validation.Field(&a.City, validation.Required, validation.Length(5, 50)),
        // State cannot be empty, and must be a string consisting of two letters in upper case
        validation.Field(&a.State, validation.Required, validation.Match(regexp.MustCompile("^[A-Z]{2}$"))),
        // State cannot be empty, and must be a string consisting of five digits
        validation.Field(&a.Zip, validation.Required, validation.Match(regexp.MustCompile("^[0-9]{5}$"))),
    )
}

func main() {
    a := Address{
        Street: "123",
        City:   "Unknown",
        State:  "Virginia",
        Zip:    "12345",
    }

    err := a.Validate()
    fmt.Println(err)
    // Output:
    // Street: the length must be between 5 and 50; State: must be in a valid format.
}