It is a lot of code having to check the login variables inside the POST handler, and i could not mark each input field individually as invalid because the generic errors array i was using did no identify which field had the error. Thus, i use more or less the same technique as with Numerus: a struct with the value and the error message. This time the input field does not have the label and extra attributes because i believe this belongs to the template: if i want do reuse the same form template, i should create a common template rather than defining everything in Go. The name is a bit different, however, because it has meaning both to the front and back ends, as it needs to be exactly the same. Writing it twice is error-prone, as with a rename i could easily forget to change one or the other, and here i see value in having that in Go, because it is also used in code.
42 lines
817 B
Go
42 lines
817 B
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) check(field *Input, ok bool, message string) bool {
|
|
if !ok {
|
|
field.Error = errors.New(v.l.Get(message))
|
|
v.AllOK = false
|
|
}
|
|
return ok
|
|
}
|