122 lines
2.5 KiB
Go
122 lines
2.5 KiB
Go
package pkg
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net/http"
|
|
"net/mail"
|
|
"strings"
|
|
)
|
|
|
|
type Attribute struct {
|
|
Key, Val string
|
|
}
|
|
|
|
type InputField struct {
|
|
Name string
|
|
Label string
|
|
Type string
|
|
Value string
|
|
Required bool
|
|
Attributes []*Attribute
|
|
Errors []error
|
|
}
|
|
|
|
func (field *InputField) FillValue(r *http.Request) {
|
|
field.Value = strings.TrimSpace(r.FormValue(field.Name))
|
|
}
|
|
|
|
type SelectOption struct {
|
|
Value string
|
|
Label string
|
|
}
|
|
|
|
type SelectField struct {
|
|
Name string
|
|
Label string
|
|
Selected string
|
|
Options []*SelectOption
|
|
Errors []error
|
|
}
|
|
|
|
func (field *SelectField) FillValue(r *http.Request) {
|
|
field.Selected = r.FormValue(field.Name)
|
|
}
|
|
|
|
func (field *SelectField) HasValidOption() bool {
|
|
for _, option := range field.Options {
|
|
if option.Value == field.Selected {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func MustGetOptions(ctx context.Context, conn *Conn, sql string, args ...interface{}) []*SelectOption {
|
|
rows, err := conn.Query(ctx, sql, args...)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
defer rows.Close()
|
|
|
|
var options []*SelectOption
|
|
for rows.Next() {
|
|
option := &SelectOption{}
|
|
err = rows.Scan(&option.Value, &option.Label)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
options = append(options, option)
|
|
}
|
|
if rows.Err() != nil {
|
|
panic(rows.Err())
|
|
}
|
|
|
|
return options
|
|
}
|
|
|
|
type FormValidator struct {
|
|
Valid bool
|
|
}
|
|
|
|
func newFormValidator() *FormValidator {
|
|
return &FormValidator{true}
|
|
}
|
|
|
|
func (v *FormValidator) AllOK() bool {
|
|
return v.Valid
|
|
}
|
|
|
|
func (v *FormValidator) CheckRequiredInput(field *InputField, message string) bool {
|
|
return v.checkInput(field, field.Value != "", message)
|
|
}
|
|
|
|
func (v *FormValidator) CheckValidEmailInput(field *InputField, message string) bool {
|
|
_, err := mail.ParseAddress(field.Value)
|
|
return v.checkInput(field, err == nil, message)
|
|
}
|
|
|
|
func (v *FormValidator) CheckPasswordConfirmation(password *InputField, confirm *InputField, message string) bool {
|
|
return v.checkInput(confirm, password.Value == confirm.Value, message)
|
|
}
|
|
|
|
func (v *FormValidator) CheckValidSelectOption(field *SelectField, message string) bool {
|
|
return v.checkSelect(field, field.HasValidOption(), message)
|
|
}
|
|
|
|
func (v *FormValidator) checkInput(field *InputField, ok bool, message string) bool {
|
|
if !ok {
|
|
field.Errors = append(field.Errors, errors.New(message))
|
|
v.Valid = false
|
|
}
|
|
return ok
|
|
}
|
|
|
|
func (v *FormValidator) checkSelect(field *SelectField, ok bool, message string) bool {
|
|
if !ok {
|
|
field.Errors = append(field.Errors, errors.New(message))
|
|
v.Valid = false
|
|
}
|
|
return ok
|
|
}
|