udemy-go-web-1/internal/forms/forms.go

63 lines
1.3 KiB
Go
Raw Normal View History

2024-06-30 15:08:47 +00:00
package forms
import (
2024-07-01 11:37:03 +00:00
"fmt"
2024-06-30 15:08:47 +00:00
"net/url"
2024-07-01 11:37:03 +00:00
"strings"
"github.com/asaskevich/govalidator"
2024-06-30 15:08:47 +00:00
)
// 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{}),
}
}
2024-07-01 11:37:03 +00:00
// Required checks required fields
func (f *Form) Required(fields ...string) {
2024-07-02 19:48:00 +00:00
for _, field := range fields {
value := f.Get(field)
if strings.TrimSpace(value) == "" {
f.Errors.Add(field, "This field cannot be blank")
}
}
2024-07-01 11:37:03 +00:00
}
2024-06-30 15:08:47 +00:00
// Has checks if form field is in post and not emtpy
2024-07-02 19:48:00 +00:00
func (f *Form) Has(field string) bool {
x := f.Get(field)
return x != ""
2024-06-30 17:35:59 +00:00
}
// Valid returns true if there are no errors, otherwise false
func (f *Form) Valid() bool {
return len(f.Errors) == 0
2024-06-30 15:08:47 +00:00
}
2024-07-01 11:37:03 +00:00
// MinLength checks for string minimum length
2024-07-02 19:48:00 +00:00
func (f *Form) MinLength(field string, length int) bool {
value := f.Get(field)
if len(value) < length {
f.Errors.Add(field, fmt.Sprintf("This field must have at least %d letters", length))
return false
}
return true
2024-07-01 11:37:03 +00:00
}
// IsEmail checks the email address
2024-07-02 19:48:00 +00:00
func (f *Form) IsEmail(field string) {
value := f.Get(field)
if !govalidator.IsEmail(value) {
f.Errors.Add(field, "Invalid email address")
}
}