Skip to content

Commit 4762e16

Browse files
committed
docs: show usage with forms of validator
1 parent 674559b commit 4762e16

1 file changed

Lines changed: 35 additions & 1 deletion

File tree

docs/EXAMPLES.md

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,10 +32,16 @@ If you run `go run .` the output will be just `-`. The version is only available
3232

3333
### JSON
3434

35-
## validator
35+
## Validator
36+
37+
Validator can be either used with HTML forms or as standalone.
3638

3739
Install the validator package: `go get github.com/bit8bytes/toolbox/validator` and use it:
3840

41+
### Standalone
42+
43+
To use `validator` standalone you need to create a new Validator (`v := validator.New()`)
44+
3945
```go
4046
package main
4147

@@ -76,3 +82,31 @@ Run `go run .`, the output will be:
7682
$ go run .
7783
key: name: msg: Name must be 'bit8bytes'
7884
```
85+
86+
### With Forms
87+
88+
To use `validator` with HTML forms you need to include the validator in your form struct.
89+
90+
```go
91+
package main
92+
93+
type form struct {
94+
Name string `form:"name"`
95+
validator.Validator `form:"-"`
96+
}
97+
98+
func postFormHandler(w http.ResponseWriter, r *http.Request) {
99+
form := form{
100+
Name: r.PostForm.Get("name"),
101+
}
102+
103+
form.Check(validator.NotBlank(tokenPlaintext), "name", "This field cannot be blank")
104+
105+
if !form.Valid() {
106+
http.Error(w, "Validation failed!", http.StatusUnprocessableEntity)
107+
return
108+
}
109+
110+
w.Write([]byte("Validation passed!"))
111+
}
112+
```

0 commit comments

Comments
 (0)