https://github.com/wuhan005/govalid
一直没有好用的表单验证库,索性写一个自己用。/ A simple Go form validator.
https://github.com/wuhan005/govalid
form-validator go validation
Last synced: about 1 year ago
JSON representation
一直没有好用的表单验证库,索性写一个自己用。/ A simple Go form validator.
- Host: GitHub
- URL: https://github.com/wuhan005/govalid
- Owner: wuhan005
- License: mit
- Created: 2020-03-18T16:53:12.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2024-09-03T08:00:22.000Z (almost 2 years ago)
- Last Synced: 2025-03-27T04:22:20.049Z (over 1 year ago)
- Topics: form-validator, go, validation
- Language: Go
- Homepage:
- Size: 104 KB
- Stars: 8
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Funding: .github/FUNDING.yml
- License: LICENSE
Awesome Lists containing this project
README
# govalid
A simple Go struct validator.
[](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, "i@github.red.",
}
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