camper/pkg/form/validator.go

54 lines
1.1 KiB
Go

/*
* SPDX-FileCopyrightText: 2023 jordi fita mas <jfita@peritasoft.com>
* SPDX-License-Identifier: AGPL-3.0-only
*/
package form
import (
"dev.tandem.ws/tandem/camper/pkg/locale"
"errors"
"net/mail"
)
type Validator struct {
l *locale.Locale
AllOK bool
}
func NewValidator(l *locale.Locale) *Validator {
return &Validator{
l: l,
AllOK: true,
}
}
func (v *Validator) CheckRequired(input *Input, message string) bool {
return v.check(input, input.Val != "", message)
}
func (v *Validator) CheckValidEmail(input *Input, message string) bool {
_, err := mail.ParseAddress(input.Val)
return v.check(input, err == nil, message)
}
func (v *Validator) CheckPasswordConfirmation(password *Input, confirm *Input, message string) bool {
return v.check(confirm, password.Val == confirm.Val, message)
}
func (v *Validator) CheckSelectedOptions(field *Select, message string) bool {
return v.check(field, field.validOptionsSelected(), message)
}
type field interface {
setError(error)
}
func (v *Validator) check(field field, ok bool, message string) bool {
if !ok {
field.setError(errors.New(v.l.Get(message)))
v.AllOK = false
}
return ok
}