https://github.com/davaddi/validation
a lib for struct field validation in go
https://github.com/davaddi/validation
go nested-objects reflection validation
Last synced: 10 months ago
JSON representation
a lib for struct field validation in go
- Host: GitHub
- URL: https://github.com/davaddi/validation
- Owner: DavadDi
- License: mit
- Created: 2017-02-28T02:44:10.000Z (about 9 years ago)
- Default Branch: master
- Last Pushed: 2018-02-08T08:19:17.000Z (about 8 years ago)
- Last Synced: 2025-04-20T01:33:08.011Z (11 months ago)
- Topics: go, nested-objects, reflection, validation
- Language: Go
- Homepage: https://www.godoc.org/github.com/DavadDi/validation
- Size: 27.3 KB
- Stars: 4
- Watchers: 3
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
validation
=====================
The Simpler Validation in go.
* Use **func(v interface{}) error** for Validater
* Support User define Validater
* Support Struct define **Validater() error** interface
* Support slice/array/pointer and netestd struct validate. Not for map now!
[](https://travis-ci.org/DavadDi/validation) [](https://coveralls.io/r/DavadDi/validation) [](http://godoc.org/github.com/DavadDi/validation) [](https://goreportcard.com/report/github.com/DavadDi/validation) [](https://img.shields.io/badge/License-MIT-brightgreen.svg)
## Install and tests
Install:
```
$go get github.com/DavadDi/validation
```
Test:
```
$go test github.com/DavadDi/validation
```
## Simple Usage
```go
package main
import (
"fmt"
"github.com/DavadDi/validation"
)
// ex01 simple use
type Person struct {
Name string `valid:"required"`
Email string `valid:"required;email"`
Age int `valid:"-"`
Sex int ``
WebSites []string `valid:"url"`
}
func main() {
web1 := "http://www.do1618.com"
web2 := "www.baidu.com"
person1 := &Person{
Name: "dave",
Email: "dwh0403@163.com",
WebSites: []string{web1, web2},
}
validater := validation.NewValidation()
res := validater.Validate(person1)
if res {
fmt.Println("Person1 validate succeed!")
} else {
fmt.Printf("Person1 validate failed. %s", validater.ErrMsg())
}
validater.Reset()
person2 := &Person{
Email: "dwh0403@163.com",
WebSites: []string{web1, web2},
}
res = validater.Validate(person2)
if !res {
fmt.Printf("Person2 validate failed. %s\n", validater.ErrMsg())
} else {
fmt.Println("Person2 validate succeed!")
}
}
```
#### Struct Tag Functions:
required
email
url
### Output:
Person1 validate succeed!
Person2 validate failed. [Name] check failed [field can't be empty or zero] [""]
## Add Use Define Validater
Use define validater **func(v interface{}) error** and add it to validation.
```go
package main
import (
"fmt"
"github.com/DavadDi/validation"
)
type Person struct {
Name string `valid:"required"`
Email string `valid:"required;email"`
Age int `valid:"required;age"`
Sex int ``
WebSites []string `valid:"url"`
}
func ageChecker(v interface{}) error {
age, ok := v.(int)
if !ok {
return validation.NewErrWrongType("int", v)
}
if age <= 0 || age > 140 {
return fmt.Errorf("age checke failed. should between [1-140], now %d", age)
}
return nil
}
func main() {
validation.AddValidater("age", ageChecker)
person1 := &Person{
Name: "dave",
Email: "dwh0403@163.com",
}
validater := validation.NewValidation()
res := validater.Validate(person1)
if res {
fmt.Println("Person1 validate succeed!")
} else {
fmt.Printf("Person1 validate failed. %s\n", validater.ErrMsg())
}
}
```
### Output:
Person1 validate failed. [Age] check failed [field can't be empty or zero] [0]
## Collaborate with Struct Interface
Use struct define validater need impl the interface **Validater() error**.
```go
package main
import (
"fmt"
"log"
"github.com/DavadDi/validation"
)
type Person struct {
Name string `valid:"required"`
Email string `valid:"required;email"`
Age int
Sex int
WebSites []string `valid:"url"`
}
func (p *Person) Validater() error {
log.Println("In our struct validater now")
if p.Age <= 0 || p.Age > 140 {
return fmt.Errorf("age checke failed. should between [1-140], now %d", p.Age)
}
return nil
}
func main() {
// Turn on debug
// validation.EnableDebug(true)
person1 := &Person{
Name: "dave",
Email: "dwh0403@163.com",
}
validater := validation.NewValidation()
res := validater.Validate(person1)
if res {
fmt.Println("Person1 validate succeed!")
} else {
fmt.Printf("Person1 validate failed. %s\n", validater.ErrMsg())
}
}
```
### Output
2017/02/28 10:29:34 In our struct validater now
Person1 validate failed. [Object] check failed [age checke failed. should between [1-140], now 0] [&main.Person{Name:"dave", Email:"dwh0403@163.com", Age:0, Sex:0, WebSites:[]string(nil)}]
## Check Ptr Field for Requried
```go
package main
import (
"fmt"
"github.com/DavadDi/validation"
)
func Bool(a bool) *bool {
return &a
}
type Person struct {
Name string `valid:"required"`
Email string `valid:"required;email"`
Age int
Sex int
IsAdmin *bool `valid:"required"` // check IsAmdin has or not
WebSites []string `valid:"url"`
}
func main() {
// Turn on debug
validation.EnableDebug(true)
person1 := &Person{
Name: "dave",
Email: "dwh0403@163.com",
IsAdmin: Bool(false),
}
validater := validation.NewValidation()
res := validater.Validate(person1)
if res {
fmt.Println("Person1 validate succeed!")
} else {
fmt.Printf("Person1 validate failed. %s\n", validater.ErrMsg())
}
}
```
Why used **IsAdmin *bool**, because sometime, we recv data from RESTFUL interface, for example:
web pass json struct:
```json
{
"name": "dave"
}
```
In go program, we define the struct below, need the both value **name** && **isAdmin**
```go
type Person struct {
Name *string `valid:"required" json:"name"`
IsAdmin *bool `valid:"required" json:"isAdmin"`
}
```
After call **json.Marshal**, valid **required** on field ptr can meet the situation.
## Debug
Turn on Debug
```go
validation.EnableDebug(true)
```
Turn off Debug
```go
validation.EnableDebug(false)
```
## LICENSE
MIT License https://choosealicense.com/licenses/mit/ More See https://choosealicense.com/licenses/