Documentation
¶
Overview ¶
Package forms provides helpers and functions to create and validate forms.
Introduction ¶
Write some documentation.
Index ¶
- Variables
- func ApplyCleaners[T any](p ValidatorsProvider, v T) T
- func ApplyValidators[T any](f Binder, v any, validators ...Validator) (errs []error)
- func Bind(r *http.Request, f FormBinder)
- func BindAs[T any](r *http.Request, options ...func(FormBinder)) *T
- func BindValues(values url.Values, f FormBinder)
- func Choices[T comparable](f Binder, choices ...ValueChoice[T])
- func DecodeValueData[IN inputData, T any](v SetterValuer[T], data IN, unmarshal func(data IN) (res *T, err error)) error
- func IterErrors(err error) iter.Seq[error]
- func IterErrorsTr(ctx context.Context, err error) iter.Seq[error]
- func MarshalValues(in any) map[string]any
- func New[T any](ctx context.Context, options ...func(FormBinder)) *T
- func RegisterTaggedValidator(fn TaggedValidatorFunc)
- func UnmarshalURLValues(values url.Values, v any) (err error)
- func UnmarshalValues(values []string, v any) (err error)
- func WithTranslator(ctx context.Context, tr Translator) context.Context
- func WrapTrError(ctx context.Context, err error) error
- type BaseValue
- func (v BaseValue[T]) Flags() ValueFlags
- func (v BaseValue[T]) IsBound() bool
- func (v BaseValue[T]) IsEmpty() bool
- func (v BaseValue[T]) IsNil() bool
- func (v BaseValue[T]) MarshalJSON() ([]byte, error)
- func (v *BaseValue[T]) Set(in T)
- func (v *BaseValue[T]) SetFlags(f ValueFlags)
- func (v *BaseValue[T]) SetValidators(validators []Validator)
- func (v BaseValue[T]) String() string
- func (v *BaseValue[T]) UnmarshalJSON(in []byte) error
- func (v *BaseValue[T]) UnmarshalValues(values []string) error
- func (v BaseValue[T]) Validators() []Validator
- func (v BaseValue[T]) Value() T
- type Binder
- type BooleanField
- type BooleanValue
- type ChoicesField
- type ChoicesProvider
- type CleanerFunc
- type ContextHolder
- type DatetimeField
- type DatetimeListField
- type DatetimeValue
- type ErrValueFlags
- type Errors
- type Field
- func (f *Field[T, V]) AddErrors(errs ...error)
- func (f *Field[T, V]) ApplyValidators(validators ...Validator)
- func (f Field[T, V]) Errors() Errors
- func (f Field[T, V]) IsBound() bool
- func (f Field[T, V]) IsEmpty() bool
- func (f Field[T, V]) IsNil() bool
- func (f *Field[T, V]) IsValid() bool
- func (f Field[T, V]) MarshalJSON() ([]byte, error)
- func (f Field[T, V]) Name() string
- func (f *Field[T, V]) Set(v T)
- func (f *Field[T, V]) SetContext(ctx context.Context)
- func (f *Field[T, V]) SetName(name string)
- func (f *Field[T, V]) SetNil()
- func (f *Field[T, V]) SetValidators(validators []Validator)
- func (f Field[T, V]) String() string
- func (f *Field[T, V]) UnmarshalFiles(files []*multipart.FileHeader) error
- func (f *Field[T, V]) UnmarshalJSON(in []byte) error
- func (f *Field[T, V]) UnmarshalValues(values []string) error
- func (f Field[T, V]) V() any
- func (f Field[T, V]) Validators() []Validator
- func (f Field[T, V]) Value() T
- type FieldFlags
- type FieldValidator
- type FieldValidatorFunc
- type File
- type FileField
- type FileListField
- type FileOpener
- type FileValue
- type FilesUnmarshaler
- type FlagSetter
- type Form
- func (f *Form) AddErrors(errs ...error)
- func (f *Form) Bind()
- func (f *Form) Context() context.Context
- func (f Form) Errors() Errors
- func (f *Form) Fields() map[string]Binder
- func (f *Form) IsBound() bool
- func (f *Form) IsValid() bool
- func (f *Form) MarshalJSON() ([]byte, error)
- func (f *Form) MarshalValues() map[string]any
- func (f *Form) SetContext(ctx context.Context)
- func (f *Form) SetFields(fields map[string]Binder)
- func (f *Form) SetInstance(instance FormBinder)
- type FormBinder
- type FormError
- type IntegerField
- type IntegerListField
- type ListField
- type ListValue
- type MimeType
- type MultipartFileOpener
- type NoopTranslator
- type NumberField
- type NumberListField
- type NumberValue
- type PivotListValue
- type Setter
- type SetterValuer
- type StringOpener
- type StringValue
- type TagContext
- type TaggedValidatorFunc
- type TaggedValidatorProvider
- type TextField
- type TextListField
- type Translator
- type TranslatorProvider
- type TypedBinder
- type URLField
- type URLListField
- type URLValue
- type URLValuesUnmarshaler
- type ValidateChecker
- type Validator
- type ValidatorProvider
- type ValidatorsProvider
- type ValueChoice
- type ValueChoices
- type ValueCleaner
- type ValueFlags
- type ValueValidator
- func Gte(n float64) ValueValidator[any]
- func IsURL(schemes ...string) ValueValidator[any]
- func Len(n int) ValueValidator[string]
- func Lte(n float64) ValueValidator[any]
- func MaxLen(n int) ValueValidator[string]
- func MinLen(n int) ValueValidator[string]
- func TypedValidator[T any](validator func(T) bool, err error) ValueValidator[T]
- type ValueValidatorFunc
- type Valuer
- type ValuesUnmarshaler
Constants ¶
This section is empty.
Variables ¶
var ( ErrFormIsBound = errors.New("form is already bound") ErrFormInvalidInput = errors.New("invalid input data") ErrUnknownContentType = errors.New("unknown content type") ErrUnexpected = Gettext("an unexpected error has occurred") )
Error definitions.
var ( // Gettext is an alias for newError (for locales extractor). Gettext = newError // Pgettext is an alias for newError (for locales extractor). Pgettext = newErrorCtx )
var ( ErrRequired = Gettext("field is required") ErrInvalidEmail = Gettext("not a valid email address") ErrInvalidURL = Gettext("invalid URL") // ErrSkipValidation is an error that is not returned and stop // any subsequent validator. ErrSkipValidation = errors.New("skip") )
Error definitions.
var DiscardEmpty = CleanerFunc[[]string](func(v []string) []string { return slices.DeleteFunc(v, func(s string) bool { return s == "" }) })
DiscardEmpty is a ValueCleaner that removes empty values from a list of string.
var ErrInvalidValue = errors.New("invalid value")
ErrInvalidValue is the error for invalid value.
var IsEmail = TypedValidator(func(v string) bool { l := len(v) c := 0 for i, x := range v { if x == '@' { if c > 0 { return false } if i == 0 { return false } if i == l-1 { return false } c++ } if unicode.Is(unicode.C, x) || unicode.Is(unicode.Space, x) { return false } } return c == 1 }, ErrInvalidEmail)
IsEmail performs a rough check of the email address. That is, it only checks for the presence of "@", only once and in the string. Control characters and spaces are not allowed.
var RequestLoaders = map[string]func(r *http.Request, f FormBinder) error{ string(MimeJSON): func(r *http.Request, f FormBinder) error { if err := json.NewDecoder(r.Body).Decode(f); err != nil { return ErrFormInvalidInput } return nil }, string(MimeURLEncoded): func(r *http.Request, f FormBinder) error { if err := r.ParseForm(); err != nil { return ErrFormInvalidInput } if err := UnmarshalURLValues(r.Form, f); err != nil { return ErrFormInvalidInput } return nil }, string(MimeMultipart): func(r *http.Request, f FormBinder) error { if err := unmarshalMultipart(r, f); err != nil { return ErrFormInvalidInput } return nil }, }
RequestLoaders contains the functions used to load a request's into a FormBinder.
Adding or removing items from RequestLoaders should only be done in a module's init function.
For example, if you need to support "text/json" as "application/json", you can add this in a module:
func init() {
RequestLoaders["text/json"] = RequestLoaders[string(forms.MimeJSON)]
}
var Required = FieldValidatorFunc(func(f Binder) error { if !f.IsBound() || f.IsEmpty() || f.IsNil() { return FatalError(ErrRequired) } return nil })
Required is a FieldValidator that returns an error when a field is null, not bound or empty.
var RequiredOrNil = FieldValidatorFunc(func(f Binder) error { if !f.IsNil() && f.IsEmpty() { return FatalError(ErrRequired) } return nil })
RequiredOrNil is a FieldValidator that returns an error when the field is empty but not null.
var Skip = FieldValidatorFunc(func(f Binder) error { if f.IsNil() || f.IsEmpty() || f.String() == "" { return ErrSkipValidation } return nil })
Skip skips subsequent validators when the field is null or empty.
var SplitLines = ValueValidatorFunc[[]string](func(f Binder, value []string) error { field, ok := f.(Setter[[]string]) if !ok { return nil } res := []string{} for _, x := range value { for l := range strings.Lines(x) { if s := strings.TrimSpace(l); s != "" { res = append(res, s) } } } field.Set(res) return nil })
SplitLines works on any []string value and populates the field after spliting each item's lines. It will trim spaces on each value.
var Trim = CleanerFunc[string](strings.TrimSpace)
Trim is a ValueCleaner that trims spaces on string values.
var ValidateTagName = "validate"
ValidateTagName is the struct field tag name used to declare validators. It can be changed in an init function if needed.
Functions ¶
func ApplyCleaners ¶
func ApplyCleaners[T any](p ValidatorsProvider, v T) T
ApplyCleaners applies the p's [ValueCleaner]s. It returns the cleaned up value.
func ApplyValidators ¶
ApplyValidators applies the given validators to the field and returns all found errors. It can run at any time, including during a form or field custom validation.
Every FieldValidator is applied. Every ValueValidator for T and is applied.
A validator that returns a FatalError or ErrSkipValidation will stops any further validation.
func Bind ¶
func Bind(r *http.Request, f FormBinder)
Bind loads the data using the method tied to the request's content-type header.
func BindAs ¶
func BindAs[T any](r *http.Request, options ...func(FormBinder)) *T
BindAs combines New and Bind in one step, returning the newly created form.
func BindValues ¶
func BindValues(values url.Values, f FormBinder)
BindValues loads the data from a url.Values input. This can be used to load values only from the URL's query string.
func Choices ¶
func Choices[T comparable](f Binder, choices ...ValueChoice[T])
Choices adds a list of ValueChoice to the field f. If it implements ChoicesProvider, the choice list is added to the field.
When it implements ValidatorProvider, a validator is added so only valid choices are accepted.
func DecodeValueData ¶
func DecodeValueData[IN inputData, T any]( v SetterValuer[T], data IN, unmarshal func(data IN) (res *T, err error), ) error
DecodeValueData is the function that decodes a value and sets its flags. It receives a SetterValuer an input ([]byte or []string) and a suitable unmarshal function.
When the unmarshal function returns nil without error, the value's flags are set to IsNil, IsEmpty, IsBound and [IsOk].
When the unmarshal function returns an ErrValueFlags error, the error is ignored and its flag is added to the existing ones.
func IterErrors ¶
IterErrors returns an iterator over an error and flatens the result. It recursively yields errors contained in the error when it implements Unwrap() []error (like errors.Join or Errors do). Every result is wrapped in a [localizedError] so its call to Error() produces a translated error.
func IterErrorsTr ¶
IterErrorsTr returns an iterator that yields errors wrapped as localized error so they can be translated when calling their Error() method.
func MarshalValues ¶
MarshalValues returns a recursive map of all values implementing Binder. It panics when "in" is not a struct.
func New ¶
func New[T any](ctx context.Context, options ...func(FormBinder)) *T
New prepares and returns a new instance of T. It panics if T is not a struct implementing FormBinder or when a field's "validate" tag does not exist.
func RegisterTaggedValidator ¶
func RegisterTaggedValidator(fn TaggedValidatorFunc)
RegisterTaggedValidator adds a new TaggedValidatorFunc to the tagged validators registry. It can be called in an init function. Any tag added here will be global.
func UnmarshalURLValues ¶
UnmarshalURLValues decode url.Values into v. v must be a pointer to a struct. Nested values are supported with a "." separator. For example, the following struct:
type nested {
Name string `json:"string"`
Meta struct {
Address string `json:"address"`
} `json:"meta"`
}
can be decoded with "?name=someone&meta.address=somewhere"
The output struct's fields support the "json" tag.
Each value name matching a struct field is decoded using UnmarshalValues while values with a prefix are sent again to this function with the prefix removed.
func UnmarshalValues ¶
UnmarshalValues decodes a list of string into v. When v implements ValuesUnmarshaler, encoding.TextUnmarshaler or encoding.BinaryUnmarshaler, their respective unmarshal methods have priority (in that order).
Otherwise, scalar values are decoded (bool, string, float, signed and unsigned integer). With encoding.TextUnmarshaler, encoding.BinaryUnmarshaler or scalar values, only the first item from values is decoded.
When v is a slice, UnmarshalValues is called on each item in values.
func WithTranslator ¶
func WithTranslator(ctx context.Context, tr Translator) context.Context
WithTranslator adds a Translator to the given context.Context.
Types ¶
type BaseValue ¶
type BaseValue[T any] struct { // contains filtered or unexported fields }
BaseValue is an implementation of Valuer. It provides a working decoder and a generic fmt.Stringer without any specialization.
func (BaseValue[T]) Flags ¶
func (v BaseValue[T]) Flags() ValueFlags
Flags returns the value's ValueFlags.
func (BaseValue[T]) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
func (*BaseValue[T]) SetFlags ¶
func (v *BaseValue[T]) SetFlags(f ValueFlags)
SetFlags replaces the value's ValueFlags.
func (*BaseValue[T]) SetValidators ¶
SetValidators implements ValidatorsProvider and sets the value's validators.
func (*BaseValue[T]) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
func (*BaseValue[T]) UnmarshalValues ¶
UnmarshalValues implement ValuesUnmarshaler.
func (BaseValue[T]) Validators ¶
Validators implements ValidatorsProvider and returns the value's validators.
type Binder ¶
type Binder interface {
fmt.Stringer
IsBound() bool
IsEmpty() bool
IsNil() bool
Errors() Errors
V() any
}
Binder describes a type that is "bound" to some data by the means of appropriate unmarshaling. It then provides informations about its state.
type BooleanField ¶
type BooleanField = Field[bool, BooleanValue]
BooleanField is a field that holds a [bool] value.
type BooleanValue ¶
BooleanValue is a Valuer for [bool] types.
func (BooleanValue) String ¶
func (v BooleanValue) String() string
func (*BooleanValue) UnmarshalValues ¶
func (v *BooleanValue) UnmarshalValues(values []string) error
UnmarshalValues implements ValuesUnmarshaler. It parses a value "on" as true.
type ChoicesField ¶
type ChoicesField[T comparable] struct { // contains filtered or unexported fields }
ChoicesField implements ChoicesProvider. It can be used to augment a Field for comparable types.
func (*ChoicesField[T]) Choices ¶
func (f *ChoicesField[T]) Choices() ValueChoices[T]
Choices returns the stored choices.
func (*ChoicesField[T]) SetChoices ¶
func (f *ChoicesField[T]) SetChoices(choices ValueChoices[T])
SetChoices sets the stored choices.
type ChoicesProvider ¶
type ChoicesProvider[T comparable] interface { Choices() ValueChoices[T] SetChoices(ValueChoices[T]) }
ChoicesProvider is an interface implemented by types than can store and return ValueChoices.
type ContextHolder ¶
ContextHolder is an interface implemented by types that can carry a context.Context.
type DatetimeField ¶
type DatetimeField = Field[time.Time, DatetimeValue]
DatetimeField is a field that holds a time.Time value.
type DatetimeListField ¶
DatetimeListField is a field that holds a list of time.Time values.
type DatetimeValue ¶
DatetimeValue is a Valuer for time.Time values. It can parse more formats than what's allowed by time.Time unmarshal functions.
func (DatetimeValue) String ¶
func (v DatetimeValue) String() string
String returns the value formatted with time.RFC3339.
func (*DatetimeValue) UnmarshalJSON ¶
func (v *DatetimeValue) UnmarshalJSON(in []byte) error
UnmarshalJSON implements json.Unmarshaler.
func (*DatetimeValue) UnmarshalValues ¶
func (v *DatetimeValue) UnmarshalValues(values []string) error
UnmarshalValues implements ValuesUnmarshaler.
type ErrValueFlags ¶
type ErrValueFlags ValueFlags
ErrValueFlags is an error that can be returned from DecodeValueData.
func (ErrValueFlags) Error ¶
func (e ErrValueFlags) Error() string
type Errors ¶
type Errors []error
Errors is an error list.
func FatalError ¶
FatalError is an error that has the effect to stop any subsequent validation.
func (Errors) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
type Field ¶
Field is a generic field that holds a value of the given type and implements Binder. It's the common building block for a specialized field.
func (*Field[T, V]) ApplyValidators ¶
ApplyValidators applies the given validators to the field and add the resulting errors to the field's error list. It can run at any time, including during a form or field custom validation.
func (*Field[T, V]) IsValid ¶
IsValid applies the field's FieldValidator and ValueValidator. Each returned error is added to the field's error list. It returns false when the error list is not empty.
func (Field[T, V]) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
func (*Field[T, V]) SetContext ¶
SetContext sets the field's context. It implements ContextHolder.
func (*Field[T, V]) SetNil ¶
func (f *Field[T, V]) SetNil()
SetNil sets the Valuer to nil if it implements Setter and FlagSetter. It only sets the nil flag and doesn't empty the value.
func (*Field[T, V]) SetValidators ¶
SetValidators implements ValidatorsProvider and sets the field's validators.
func (*Field[T, V]) UnmarshalFiles ¶
func (f *Field[T, V]) UnmarshalFiles(files []*multipart.FileHeader) error
UnmarshalFiles implements FilesUnmarshaler. It only works on [Valuer]s implementing FilesUnmarshaler themselves.
func (*Field[T, V]) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler. It always returns nil and errors, if any, are added to the field's error list.
func (*Field[T, V]) UnmarshalValues ¶
UnmarshalValues implement ValuesUnmarshaler. It always returns nil and errors, if any, are added to the field's error list.
func (Field[T, V]) Validators ¶
Validators implements ValidatorsProvider and returns the value's validators.
type FieldFlags ¶
type FieldFlags byte
FieldFlags is a field's flag list.
const ( // ValidatedField indicates a field has been validated. ValidatedField FieldFlags = 1 << iota )
type FieldValidator ¶
FieldValidator describes a field validator (not its value).
type FieldValidatorFunc ¶
FieldValidatorFunc is a FieldValidator.
func (FieldValidatorFunc) ValidateField ¶
func (c FieldValidatorFunc) ValidateField(f Binder) error
ValidateField implements FieldValidator.
type FileListField ¶
FileListField is a field that holds a list of File values.
type FileOpener ¶
type FileOpener interface {
Open() (io.ReadCloser, error)
Filename() string
Size() int64
Header() textproto.MIMEHeader
}
FileOpener describes an opener interface. Its [Open] function must return an io.ReadCloser.
type FileValue ¶
FileValue is a Valuer for uploaded files. It can open files submitted as multipart.FileHeader or strings from JSON or url values.
func (*FileValue) UnmarshalFiles ¶
func (v *FileValue) UnmarshalFiles(files []*multipart.FileHeader) error
UnmarshalFiles imlements FilesUnmarshaler. It decodes a the first file into a MultipartFileOpener.
func (*FileValue) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler. It decodes the content as a string and produces a StringOpener.
func (*FileValue) UnmarshalValues ¶
UnmarshalValues implements ValuesUnmarshaler. It decodes the content as a string and produces a StringOpener.
type FilesUnmarshaler ¶
type FilesUnmarshaler interface {
UnmarshalFiles([]*multipart.FileHeader) error
}
FilesUnmarshaler is an interface implemented by types than can load a multipart.FileHeader list.
type FlagSetter ¶
type FlagSetter interface {
SetFlags(f ValueFlags)
}
FlagSetter describes a type that can sets its flags.
type Form ¶
type Form struct {
// contains filtered or unexported fields
}
Form is our based type for form composition.
func (*Form) Fields ¶
Fields returns the form's registered Binder fields. Their respective name matches the name used during url.Values unmarshaling (with dot separated prefix and name for nested values).
func (*Form) MarshalJSON ¶
MarshalJSON implement json.Marshaler.
func (*Form) MarshalValues ¶
MarshalValues calls MarshalValues on the form's concrete instance.
func (*Form) SetContext ¶
SetContext sets the form's context. It implements ContextHolder.
func (*Form) SetInstance ¶
func (f *Form) SetInstance(instance FormBinder)
SetInstance is used by New and will panic if called more than once.
type FormBinder ¶
type FormBinder interface {
Fields() map[string]Binder
Errors() Errors
AddErrors(...error)
IsBound() bool
Bind()
IsValid() bool
}
FormBinder is the interface implented by types that can act as a form.
type FormError ¶
type FormError struct {
// contains filtered or unexported fields
}
FormError is a form's or field's error that contains an error message and arguments.
func (FormError) Translate ¶
func (p FormError) Translate(tr Translator) string
Translate returns the translated error using the given translator.
type IntegerField ¶
type IntegerField = NumberField[int]
IntegerField is a field that holds an [int] value.
type IntegerListField ¶
type IntegerListField = NumberListField[int]
IntegerListField is a field that holds a list of [int] values.
type ListField ¶
ListField is a list field of items T with a matching Valuer. A ListField is not necessary for unmarshaling and you can simply use Field[[]T, ListValue[T, V]] for it to work. This type, however, applies the validators to each item.
func (*ListField[T, V]) IsValid ¶
IsValid first applies Field.IsValid and then perform the validation on each item.
type ListValue ¶
ListValue is a generic Valuer for list of values. It works by wrapping unmarshal calls to the Valuer V and then set its own value from the collected results.
func (ListValue[T, V]) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
func (ListValue[T, V]) String ¶
String returns a simple comma separated list of each values' String() result.
func (*ListValue[T, V]) UnmarshalFiles ¶
func (v *ListValue[T, V]) UnmarshalFiles(files []*multipart.FileHeader) error
UnmarshalFiles implements FilesUnmarshaler. It only works on Valuer items implementing FilesUnmarshaler themselves.
func (*ListValue[T, V]) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
func (*ListValue[T, V]) UnmarshalValues ¶
UnmarshalValues implements ValuesUnmarshaler.
type MultipartFileOpener ¶
type MultipartFileOpener struct {
*multipart.FileHeader
}
MultipartFileOpener is a FileOpener implementation wrapping multipart.FileHeader.
func (*MultipartFileOpener) Filename ¶
func (o *MultipartFileOpener) Filename() string
Filename implements FileOpener.
func (*MultipartFileOpener) Header ¶
func (o *MultipartFileOpener) Header() textproto.MIMEHeader
Header implements FileOpener.
func (*MultipartFileOpener) MarshalJSON ¶
func (o *MultipartFileOpener) MarshalJSON() ([]byte, error)
MarshalJSON implement json.Marshaler.
func (*MultipartFileOpener) Open ¶
func (o *MultipartFileOpener) Open() (io.ReadCloser, error)
Open implements FileOpener.
func (*MultipartFileOpener) Size ¶
func (o *MultipartFileOpener) Size() int64
Size implements FileOpener.
type NoopTranslator ¶
type NoopTranslator struct{}
NoopTranslator is a dummy translator.
func (NoopTranslator) Gettext ¶
func (NoopTranslator) Gettext(s string, args ...any) string
Gettext implements Translator.
func (NoopTranslator) Pgettext ¶
func (NoopTranslator) Pgettext(_, s string, args ...any) string
Pgettext implements Translator.
type NumberField ¶
type NumberField[T numberType] struct {
Field[T, NumberValue[T]]
ChoicesField[T]
}
NumberField is a field that holds a given number type.
type NumberListField ¶
type NumberListField[T numberType] struct {
ListField[T, ListValue[T, NumberValue[T]]]
ChoicesField[T]
}
NumberListField is a field that holds a list of number values.
type NumberValue ¶
type NumberValue[T numberType] struct {
BaseValue[T]
}
NumberValue is a Valuer for all int, uint and float types. Its decoder supports int and uint types with trailing zero decimals.
func (NumberValue[T]) String ¶
func (v NumberValue[T]) String() string
String returns the number formatted according to its type.
func (*NumberValue[T]) UnmarshalJSON ¶
func (v *NumberValue[T]) UnmarshalJSON(in []byte) error
UnmarshalJSON implements json.Unmarshaler.
func (*NumberValue[T]) UnmarshalValues ¶
func (v *NumberValue[T]) UnmarshalValues(values []string) error
UnmarshalValues implements ValuesUnmarshaler.
type PivotListValue ¶
PivotListValue is a Valuer that holds a list of T items. Decoding uses an intermediate ListValue with PT type and PV Valuer. This is useful when you need to compose list of types but need some cleaners to run on the intermediate type first. For example, a URL list would be PivotListValue[url.URL, URLValue, string, StringValue].
func (*PivotListValue[T, V, PT, PV]) UnmarshalJSON ¶
func (v *PivotListValue[T, V, PT, PV]) UnmarshalJSON(in []byte) error
UnmarshalJSON implements json.Unmarshaler.
func (*PivotListValue[T, V, PT, PV]) UnmarshalValues ¶
func (v *PivotListValue[T, V, PT, PV]) UnmarshalValues(values []string) error
UnmarshalValues implements ValuesUnmarshaler.
type Setter ¶
type Setter[T any] interface { Set(T) }
Setter describes a type that can sets its value.
type SetterValuer ¶
type SetterValuer[T any] interface { Valuer[T] Setter[T] FlagSetter }
SetterValuer describes a Valuer, Setter and FlagSetter type.
type StringOpener ¶
type StringOpener []byte
StringOpener is a FileOpener implementation using bytes.
func (StringOpener) Filename ¶
func (o StringOpener) Filename() string
Filename implements FileOpener.
func (StringOpener) Header ¶
func (o StringOpener) Header() textproto.MIMEHeader
Header implements FileOpener.
func (StringOpener) MarshalJSON ¶
func (o StringOpener) MarshalJSON() ([]byte, error)
MarshalJSON implement json.Marshaler.
func (StringOpener) Open ¶
func (o StringOpener) Open() (io.ReadCloser, error)
Open implements FileOpener.
type StringValue ¶
StringValue is an alias to BaseValue for [string] type.
type TagContext ¶
type TagContext struct {
Form FormBinder
Field Binder
Context context.Context
}
TagContext is the parameter passed to a tagged validation function.
type TaggedValidatorFunc ¶
type TaggedValidatorFunc func(name, args string, tc *TagContext) (Validator, bool)
TaggedValidatorFunc is a function called to get a Validator from a tag. The function returns a Validator (can be nil) and whether the name was found.
type TaggedValidatorProvider ¶
type TaggedValidatorProvider interface {
GetTaggedValidator(name, args string, tc *TagContext) (Validator, bool)
}
TaggedValidatorProvider is an interface that describes a type providing its custom tagged validators.
type TextField ¶
type TextField struct {
Field[string, StringValue]
ChoicesField[string]
}
TextField is a field that holds a [string] value.
type TextListField ¶
type TextListField struct {
ListField[string, ListValue[string, StringValue]]
ChoicesField[string]
}
TextListField is a field that holds a list of [string] values.
type Translator ¶
type Translator interface {
Gettext(string, ...any) string
Pgettext(ctx, str string, vars ...any) string
}
Translator describes a type that implements a translation method.
func GetTranslator ¶
func GetTranslator(ctx context.Context) Translator
GetTranslator returns the Translator from the context.
type TranslatorProvider ¶
type TranslatorProvider interface {
Translator() Translator
SetTranslator(Translator)
}
TranslatorProvider describes a type that can store and return a Translator.
type TypedBinder ¶
TypedBinder describes a Binder with its Value method.
type URLListField ¶
type URLListField = ListField[url.URL, PivotListValue[url.URL, URLValue, string, StringValue]]
URLListField is a field that holds a list of url.URL values.
type URLValue ¶
URLValue is a Valuer that can decode url.URL values. Input values are decoded using url.Parse and no further URL validation is performed.
func (URLValue) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
func (*URLValue) UnmarshalJSON ¶
UnmarshalJSON decodes an url.URL from a JSON string.
type URLValuesUnmarshaler ¶
URLValuesUnmarshaler is an interface implemented by types with a custom url.Values decoder. This can be implemented by a Form instance for special use cases.
type ValidateChecker ¶
type ValidateChecker interface {
Validate() error
}
ValidateChecker describes a type that can bring its own validation method. The returned error is added to the error list. To return several errors at once, one can use Errors or errors.Join.
type Validator ¶
type Validator any
Validator describes a generic validator. By default, it can be anything but, once attached to a field, relevant interfaces are called during cleanup and validation steps.
type ValidatorProvider ¶
type ValidatorProvider interface {
IsValid() bool
}
ValidatorProvider describes a type that provides a validation check method.
type ValidatorsProvider ¶
type ValidatorsProvider interface {
Validators() []Validator
SetValidators(validators []Validator)
}
ValidatorsProvider is an interface implemented by types than can store and return a list of Validator.
type ValueChoice ¶
type ValueChoice[T comparable] struct { Name string Value T }
ValueChoice is a key/value pair used by ValueChoices.
func Choice ¶
func Choice[T comparable](name string, value T) ValueChoice[T]
Choice returns a new ValueChoice instance.
func (ValueChoice[T]) In ¶
func (c ValueChoice[T]) In(values []T) bool
In returns true when the choice is present in a list of values.
type ValueChoices ¶
type ValueChoices[T comparable] []ValueChoice[T]
ValueChoices is a key/value pair and also a ValueValidator. It can be set directly as a validator to limit the possible choices. To set the validator and have the choice list available, see Choices.
func (ValueChoices[T]) String ¶
func (c ValueChoices[T]) String() string
func (ValueChoices[T]) ValidateValue ¶
func (c ValueChoices[T]) ValidateValue(f Binder, v T) error
ValidateValue checks that the value v exists in the choices.
type ValueCleaner ¶
type ValueCleaner[T any] interface { Clean(T) T }
ValueCleaner describes a value cleaner.
type ValueFlags ¶
type ValueFlags byte
ValueFlags holds the flags a value can get.
const ( // IsEmpty is the flag for an empty value. IsEmpty ValueFlags = 1 << iota // IsBound is the flag for a bound value. IsBound // IsNil is the flag for a nil value. IsNil )
func (ValueFlags) IsBound ¶
func (f ValueFlags) IsBound() bool
IsBound returns true when IsBound is present in the flags.
func (ValueFlags) IsEmpty ¶
func (f ValueFlags) IsEmpty() bool
IsEmpty returns true when IsEmpty is present in the flags.
func (ValueFlags) IsNil ¶
func (f ValueFlags) IsNil() bool
IsNil returns true when IsNil is present in the flags.
type ValueValidator ¶
ValueValidator describes a value validator.
func Gte ¶
func Gte(n float64) ValueValidator[any]
Gte is an integer validator that checks if a value is greater or equal than a parameter.
func IsURL ¶
func IsURL(schemes ...string) ValueValidator[any]
IsURL checks that the input value is a valid URL that matches the given schemes and has a hostname. It works on [string] and url.URL values.
func Len ¶
func Len(n int) ValueValidator[string]
Len is a string validator thats checks if it contains exactly n characters.
func Lte ¶
func Lte(n float64) ValueValidator[any]
Lte is an integer validator that checks if a value is lower or equal than a parameter.
func MaxLen ¶
func MaxLen(n int) ValueValidator[string]
MaxLen is a string validator thats checks if it contains at most n characters.
func MinLen ¶
func MinLen(n int) ValueValidator[string]
MinLen is a string validator thats checks if it contains at least n characters.
func TypedValidator ¶
func TypedValidator[T any](validator func(T) bool, err error) ValueValidator[T]
TypedValidator is a helper function that returns a ValueValidator from a validation function and an error message. The resulting validator only applies on a bound or not null field.
type ValueValidatorFunc ¶
ValueValidatorFunc is a ValueValidator.
func (ValueValidatorFunc[T]) ValidateValue ¶
func (c ValueValidatorFunc[T]) ValidateValue(f Binder, v T) error
ValidateValue implements ValueValidator.
type Valuer ¶
type Valuer[T any] interface { fmt.Stringer json.Marshaler Value() T Flags() ValueFlags IsBound() bool IsNil() bool IsEmpty() bool }
Valuer is the interface implemented by types that can load and decode input data.
type ValuesUnmarshaler ¶
ValuesUnmarshaler is an interface implemented by types with a custom url.Values item decoder.