Server-side form validation 1

This commit is contained in:
Muyao CHEN
2024-06-30 17:08:47 +02:00
parent 7294254e13
commit 8394832428
6 changed files with 59 additions and 2 deletions

18
internal/forms/errors.go Normal file
View 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
View 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 != ""
}