docs(examples): add a basic and a more complex example in examples dir

This commit is contained in:
2021-08-22 03:35:48 +01:00
parent c1121a5575
commit 0d7fd387a6
2 changed files with 148 additions and 0 deletions

38
examples/basic/basic.go Normal file
View File

@@ -0,0 +1,38 @@
package main
import (
"fmt"
"github.com/romdo/go-validate"
)
type Order struct {
Books []*Book `json:"books"`
}
type Book struct {
Title string `json:"title"`
Author string `json:"author"`
}
func (s *Book) Validate() error {
var errs error
if s.Title == "" {
errs = validate.Append(errs, &validate.Error{
Field: "Title", Msg: "is required",
})
}
// Helper to perform the same kind of check as above for Title.
errs = validate.Append(errs, validate.RequireField("Author", s.Author))
return errs
}
func main() {
errs := validate.Validate(&Order{Books: []*Book{{Title: ""}}})
for _, err := range validate.Errors(errs) {
fmt.Println(err.Error())
}
}