Server-side form validation 1
This commit is contained in:
18
internal/forms/errors.go
Normal file
18
internal/forms/errors.go
Normal file
@ -0,0 +1,18 @@
|
||||
package forms
|
||||
|
||||
type errors map[string][]string
|
||||
|
||||
// Add adds an error message for a given form field
|
||||
func (e errors) Add(field, message string) {
|
||||
e[field] = append(e[field], message)
|
||||
}
|
||||
|
||||
// Get returns the first error message
|
||||
func (e errors) Get(field string) string {
|
||||
es := e[field]
|
||||
|
||||
if len(es) == 0 {
|
||||
return ""
|
||||
}
|
||||
return es[0]
|
||||
}
|
26
internal/forms/forms.go
Normal file
26
internal/forms/forms.go
Normal file
@ -0,0 +1,26 @@
|
||||
package forms
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
// Form creates a custom form struct, embeds a url.Values object
|
||||
type Form struct {
|
||||
url.Values
|
||||
Errors errors
|
||||
}
|
||||
|
||||
// New initializes a form struct
|
||||
func New(data url.Values) *Form {
|
||||
return &Form{
|
||||
data,
|
||||
errors(map[string][]string{}),
|
||||
}
|
||||
}
|
||||
|
||||
// Has checks if form field is in post and not emtpy
|
||||
func (f *Form) Has(field string, r *http.Request) bool {
|
||||
x := r.Form.Get(field)
|
||||
return x != ""
|
||||
}
|
Reference in New Issue
Block a user