dongyanghan0556 2018-12-29 13:03
浏览 48
已采纳

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

I use Joi to do object schema and data validation in JavaScript. In Golang, I know how to do schema validation, but how do I do data validation?

Is there a Joi equivalient for Golang? I am aware of Godog, but it hasn't reached 1.0 yet.

  • 写回答

1条回答 默认 最新

  • duanquan1207 2018-12-29 14:30
    关注

    Try ozzo-validation 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.
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥15 流式socket文件传输答疑
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接
  • ¥15 MATLAB中使用parfor,矩阵Removal的有效索引在parfor循环中受限制
  • ¥20 Win 10 LTSC 1809版本如何无损提升到20H1版本
  • ¥50 win10 LTSC 虚拟键盘不弹出