Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/wuhan005/govalid

一直没有好用的表单验证库,索性写一个自己用。/ A simple Go form validator.
https://github.com/wuhan005/govalid

form-validator go validation

Last synced: about 10 hours ago
JSON representation

一直没有好用的表单验证库,索性写一个自己用。/ A simple Go form validator.

Awesome Lists containing this project

README

        

# govalid

A simple Go struct validator.

[![Go Report Card](https://goreportcard.com/badge/github.com/wuhan005/govalid)](https://goreportcard.com/report/github.com/wuhan005/govalid)

## Quick Start

```bash
go get -u github.com/wuhan005/govalid
```

```go
v := struct {
Name string `valid:"required;username" label:"昵称"`
ID int `valid:"required;min:0;max:999" label:"用户编号"`
Mail string `valid:"required;email" label:""`
}{
"e99_", 1990, "[email protected].",
}

errs, ok := govalid.Check(v)
if !ok {
for _, err := range errs {
fmt.Println(err)
}
}
```

Output:

```text
昵称的最后一个字符不能为下划线
用户编号应小于999
不是合法的电子邮箱格式
```

## Customize Error Message

```go
govalid.SetMessageTemplates(map[string]string{
"required": "can't be null.",
"min": "must bigger than %v.",
})
```

## Customize Error Check Function

```go
func main() {
// set your error message.
govalid.SetMessageTemplates(map[string]string{
"mycheck": "content cann't contain 'e99'.",
})

// add new check function
govalid.Checkers["mycheck"] = func(c govalid.CheckerContext) *govalid.ErrContext {
errCtx := govalid.NewErrorContext(c)
value, ok := ctx.Value.(string)
if !ok {
return MakeCheckerParamError(c)
}
if strings.Contains(value, "e99") {
return ctx
}
// if the check passed, return nil.
return nil
}

r := struct {
Content string `valid:"mycheck"`
}{
"helloe99",
}

errs, ok := govalid.Check(v)
if !ok {
for _, err := range errs {
fmt.Println(err)
}
}
}
```

## Special Thanks

https://github.com/jiazhoulvke/echo-form

## LICENSE

MIT