67 lines
1.8 KiB
Go
67 lines
1.8 KiB
Go
|
package form
|
||
|
|
||
|
import (
|
||
|
"errors"
|
||
|
"net/mail"
|
||
|
"net/url"
|
||
|
"strconv"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
|
type Validator struct {
|
||
|
Valid bool
|
||
|
}
|
||
|
|
||
|
func NewValidator() *Validator {
|
||
|
return &Validator{true}
|
||
|
}
|
||
|
|
||
|
func (v *Validator) AllOK() bool {
|
||
|
return v.Valid
|
||
|
}
|
||
|
|
||
|
func (v *Validator) CheckRequiredInput(field *InputField, message string) bool {
|
||
|
return v.checkInput(field, field.Val != "", message)
|
||
|
}
|
||
|
|
||
|
func (v *Validator) CheckInputMinLength(field *InputField, min int, message string) bool {
|
||
|
return v.checkInput(field, len(field.Val) >= min, message)
|
||
|
}
|
||
|
|
||
|
func (v *Validator) CheckValidEmailInput(field *InputField, message string) bool {
|
||
|
_, err := mail.ParseAddress(field.Val)
|
||
|
return v.checkInput(field, err == nil, message)
|
||
|
}
|
||
|
|
||
|
func (v *Validator) CheckPasswordConfirmation(password *InputField, confirm *InputField, message string) bool {
|
||
|
return v.checkInput(confirm, password.Val == confirm.Val, message)
|
||
|
}
|
||
|
|
||
|
func (v *Validator) CheckValidURL(field *InputField, message string) bool {
|
||
|
_, err := url.ParseRequestURI(field.Val)
|
||
|
return v.checkInput(field, err == nil, message)
|
||
|
}
|
||
|
|
||
|
func (v *Validator) CheckValidDate(field *InputField, message string) bool {
|
||
|
_, err := time.Parse("2006-01-02", field.Val)
|
||
|
return v.checkInput(field, err == nil, message)
|
||
|
}
|
||
|
|
||
|
func (v *Validator) CheckValidInteger(field *InputField, min int, max int, message string) bool {
|
||
|
value, err := strconv.Atoi(field.Val)
|
||
|
return v.checkInput(field, err == nil && value >= min && value <= max, message)
|
||
|
}
|
||
|
|
||
|
func (v *Validator) CheckValidDecimal(field *InputField, min float64, max float64, message string) bool {
|
||
|
value, err := strconv.ParseFloat(field.Val, 64)
|
||
|
return v.checkInput(field, err == nil && value >= min && value <= max, message)
|
||
|
}
|
||
|
|
||
|
func (v *Validator) checkInput(field *InputField, ok bool, message string) bool {
|
||
|
if !ok {
|
||
|
field.Errors = append(field.Errors, errors.New(message))
|
||
|
v.Valid = false
|
||
|
}
|
||
|
return ok
|
||
|
}
|