forms

package
v0.0.0-...-60192f8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 26, 2024 License: AGPL-3.0 Imports: 14 Imported by: 0

Documentation

Overview

Package forms provides helpers and functions to create and validate forms.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidType is the error for invalid type.
	ErrInvalidType = errors.New("invalid type")
	// ErrInvalidValue is the for invalid value.
	ErrInvalidValue = errors.New("invalid value")
)
View Source
var (
	ErrRequired     = Gettext("field is required")         // ErrRequired is a required field
	ErrInvalidEmail = Gettext("not a valid email address") // ErrInvalidEmail is an invalid e-mail address
	ErrInvalidURL   = Gettext("invalid URL")               // ErrInvalidURL is an invalid URL
)
View Source
var ErrUnexpected = Gettext("an unexpected error has occurred")

ErrUnexpected is an error that can be used during custom validation or form actions.

View Source
var Gettext = newError

Gettext is an alias for newError so it can be picked up by a locales extractor.

View Source
var IsEmail = StringValidator(func(v string) bool {
	return strings.Count(v, "@") == 1 && !(strings.HasPrefix(v, "@") || strings.HasSuffix(v, "@"))
}, 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.

View Source
var NilValue = []byte{0}

NilValue is a text null value. In an URL of form value, it would be a field with %00 value. (name=%00).

Functions

func Bind

func Bind(f Binder, r *http.Request)

Bind loads and validates the data using the method tied to the request's content-type header.

func DefaultListConverter

func DefaultListConverter(values []Field) interface{}

DefaultListConverter is a default fieldConverter that simply returns a list of interface{} items.

func Required

func Required(f Field) error

Required check that the field is not null or empty.

func RequiredOrNil

func RequiredOrNil(f Field) error

RequiredOrNil checks that the field is not empty if it's not null.

func Trim

func Trim(f Field) error

Trim return a validator that trims spaces from the value when it's a string.

func UnmarshalJSON

func UnmarshalJSON(f Binder, r io.Reader)

UnmarshalJSON decodes JSON values into the form. It does so by decoding first the input value into a map of raw values. Then each register field that's present in the resulting map is decoded.

func UnmarshalValues

func UnmarshalValues(f Binder, values url.Values)

UnmarshalValues decodes url encoded values into the form. It decodes every item into a map of values that are passed to each field's UnmarshalText method.

func Validate

func Validate(input interface{})

Validate performs all the fields validation and, if the form is a FormValidator, the form.Validate() method.

Types

type AnyBinder

type AnyBinder interface {
	BindAny(contentType string, r *http.Request)
}

AnyBinder describes a form that provides its own binding method for unknown content-type. One can use it to bind from multipart data, plain text, etc.

type BaseField

type BaseField struct {
	// contains filtered or unexported fields
}

BaseField is a basic field that holds the field's name and its bound and nil state.

func NewBaseField

func NewBaseField(name string, validators ...FieldValidator) *BaseField

NewBaseField returns a new BaseField instance that is considered null. Until it's set or bound, it will stay that way.

func (*BaseField) IsBound

func (f *BaseField) IsBound() bool

IsBound returns true if the field is bound.

func (*BaseField) IsNil

func (f *BaseField) IsNil() bool

IsNil returns true if the field's value is null.

func (*BaseField) Name

func (f *BaseField) Name() string

Name returns the field's name.

func (*BaseField) SetBind

func (f *BaseField) SetBind()

SetBind marks the field as bound.

func (*BaseField) SetNil

func (f *BaseField) SetNil(value interface{})

SetNil sets the nil state of the field, based on the passed value.

func (*BaseField) SetValidators

func (f *BaseField) SetValidators(validators ...FieldValidator)

SetValidators sets new validators for a field.

func (*BaseField) Validators

func (f *BaseField) Validators() []FieldValidator

Validators returns the field's validator list.

type Binder

type Binder interface {
	Fields() []*FormField
	Get(string) *FormField
	AddErrors(string, ...error)
	IsBound() bool
	Bind()
	IsValid() bool
}

Binder describes the basic needed method for a form that can be bound from JSON or URL values.

type BooleanField

type BooleanField struct {
	*BaseField
	// contains filtered or unexported fields
}

BooleanField is a boolean field (true/false).

func NewBooleanField

func NewBooleanField(name string, validators ...FieldValidator) *BooleanField

NewBooleanField return a BooleanField instance.

func (*BooleanField) Set

func (f *BooleanField) Set(value interface{}) bool

Set sets the field's value.

func (*BooleanField) String

func (f *BooleanField) String() string

String returns the field's string value.

func (*BooleanField) UnmarshalJSON

func (f *BooleanField) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the input value into a string or a nil value.

func (*BooleanField) UnmarshalText

func (f *BooleanField) UnmarshalText(text []byte) error

UnmarshalText decodes the input text value into a string or nil value.

func (*BooleanField) Value

func (f *BooleanField) Value() interface{}

Value returns the field's actuall value.

type ChoiceField

type ChoiceField struct {
	Field
	// contains filtered or unexported fields
}

ChoiceField is a text field with a limited possible values.

func NewChoiceField

func NewChoiceField(name string, choices Choices, validators ...FieldValidator) *ChoiceField

NewChoiceField returns a ChoiceField instance.

func (*ChoiceField) Choices

func (f *ChoiceField) Choices() Choices

Choices returns the list of possible values.

func (*ChoiceField) Validate

func (f *ChoiceField) Validate(_ Field) error

Validate performs the field's validation.

type Choices

type Choices [][2]string

Choices is a list of valid values (value and name).

type DatetimeField

type DatetimeField struct {
	*BaseField
	// contains filtered or unexported fields
}

DatetimeField is a datetime field.

func NewDatetimeField

func NewDatetimeField(name string, validators ...FieldValidator) *DatetimeField

NewDatetimeField return a DatetimeField instance.

func (*DatetimeField) Set

func (f *DatetimeField) Set(value interface{}) bool

Set sets the field's value.

func (*DatetimeField) String

func (f *DatetimeField) String() string

String returns the field's string value.

func (*DatetimeField) UnmarshalJSON

func (f *DatetimeField) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the input value into a string or a nil value.

func (*DatetimeField) UnmarshalText

func (f *DatetimeField) UnmarshalText(text []byte) error

UnmarshalText decodes the input text value into a string or nil value.

func (*DatetimeField) Value

func (f *DatetimeField) Value() interface{}

Value returns the field's actuall value.

type Errors

type Errors []error

Errors is an error list.

func ValidateField

func ValidateField(f Field, validators ...FieldValidator) Errors

ValidateField performs the field validation and/or alteration.

func (Errors) Error

func (e Errors) Error() string

func (Errors) MarshalJSON

func (e Errors) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON serialization of an error list.

type Field

type Field interface {
	Name() string
	IsBound() bool
	IsNil() bool
	Set(value interface{}) bool
	UnmarshalJSON([]byte) error
	UnmarshalText([]byte) error
	Value() interface{}
	String() string
	Validators() []FieldValidator
	SetValidators(...FieldValidator)
}

Field describes a form field.

func NewListField

func NewListField(name string, constructor fieldConstructor, converter fieldConverter, validators ...FieldValidator) Field

NewListField return a ListField instance. It needs a constructor and a converter. Validators at this stage are only applied to the whole field. If you need a validator for each received value, it must come with the field returned by a custom constructor.

type FieldChoices

type FieldChoices interface {
	Choices() Choices
}

FieldChoices describes a field that can return a list of possible values.

type FieldValidator

type FieldValidator func(f Field) error

FieldValidator is a function that validates and/or alters a field.

func Chain

func Chain(validators ...FieldValidator) FieldValidator

Chain applies multiple validators but stops at the first error.

func Gte

func Gte(value int) FieldValidator

Gte returns a integer validator that checks if a value is greater or equal than a parameter.

func IsValidURL

func IsValidURL(schemes ...string) FieldValidator

IsValidURL checks that the input value is a valid URL and matches the given schemes.

func Lte

func Lte(value int) FieldValidator

Lte returns a integer validator that checks if a value is lower or equal than a parameter.

func Optional

func Optional(validators ...FieldValidator) FieldValidator

Optional applies multiple validators only when the field value is set and not empty or nil.

func StringValidator

func StringValidator(validator func(v string) bool, err error) FieldValidator

StringValidator is a helper function that returns a validator from a simple function and an error message.

type Form

type Form struct {
	// contains filtered or unexported fields
}

Form is a list of fields.

func Must

func Must(fields ...Field) *Form

Must returns a new Form instance and panics if there was any error.

func New

func New(fields ...Field) (*Form, error)

New returns a new Form instance.

func (*Form) AddErrors

func (f *Form) AddErrors(name string, errorList ...error)

AddErrors adds an error to the form.

func (*Form) AllErrors

func (f *Form) AllErrors() map[string]Errors

AllErrors returns the form's error map (including field errors).

func (*Form) Bind

func (f *Form) Bind()

Bind set the form as bound. As it's called before validation, it can be used to set default values, when needs be.

func (*Form) Context

func (f *Form) Context() context.Context

Context returns the form current context.

func (*Form) Errors

func (f *Form) Errors() Errors

Errors returns the form's non-field error list.

func (*Form) FieldMap

func (f *Form) FieldMap() map[string]*FormField

FieldMap returns a map of all fields.

func (*Form) Fields

func (f *Form) Fields() []*FormField

Fields returns the form's field list.

func (*Form) Get

func (f *Form) Get(name string) *FormField

Get returns a field by its name, or nil when it doesn't exist.

func (*Form) IsBound

func (f *Form) IsBound() bool

IsBound returns true if the form has been bound to input data.

func (*Form) IsValid

func (f *Form) IsValid() bool

IsValid returns true if the form has no error.

func (*Form) MarshalJSON

func (f *Form) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON serialization of a form.

func (*Form) SetContext

func (f *Form) SetContext(ctx context.Context) *Form

SetContext set the new form's context.

func (*Form) SetLocale

func (f *Form) SetLocale(tr Translator)

SetLocale sets the form current locale.

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) Error

func (p FormError) Error() string

Error returns the untranslated error.

func (FormError) Is

func (p FormError) Is(err error) bool

Is implements error identification.

func (FormError) Translate

func (p FormError) Translate(tr Translator) string

Translate returns the translated error using the given translator.

func (FormError) Unwrap

func (p FormError) Unwrap() error

Unwrap implements error unwrap.

type FormField

type FormField struct {
	Field
	Errors Errors
}

FormField is a Field with its errors.

func (*FormField) Choices

func (f *FormField) Choices() Choices

Choices returns the choice list of a field, if the wrapped field implements the FieldChoices interface.

func (*FormField) MarshalJSON

func (f *FormField) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON serialization of a field.

type IntegerField

type IntegerField struct {
	*BaseField
	// contains filtered or unexported fields
}

IntegerField is an integer field.

func NewIntegerField

func NewIntegerField(name string, validators ...FieldValidator) *IntegerField

NewIntegerField returns a IntegerField instance.

func (*IntegerField) Set

func (f *IntegerField) Set(value interface{}) bool

Set sets the field's value.

func (*IntegerField) String

func (f *IntegerField) String() string

String returns the field's string value.

func (*IntegerField) UnmarshalJSON

func (f *IntegerField) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the input value into a string or a nil value.

func (*IntegerField) UnmarshalText

func (f *IntegerField) UnmarshalText(text []byte) error

UnmarshalText decodes the input text value into a string or nil value.

func (*IntegerField) Value

func (f *IntegerField) Value() interface{}

Value returns the field's actuall value.

type ListField

type ListField struct {
	*BaseField
	// contains filtered or unexported fields
}

ListField is a field that implement decoding and encoding of values in lists.

func (*ListField) Choices

func (f *ListField) Choices() Choices

Choices returns the field choice list.

func (*ListField) InChoices

func (f *ListField) InChoices(value string) bool

InChoices returns true if value is in the field choice list.

func (*ListField) Set

func (f *ListField) Set(value interface{}) bool

Set sets the field's value.

func (*ListField) SetChoices

func (f *ListField) SetChoices(choices Choices)

SetChoices sets the field choice list.

func (*ListField) String

func (f *ListField) String() string

String returns the field's string value.

func (*ListField) UnmarshalJSON

func (f *ListField) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the input value into a string or a nil value.

func (*ListField) UnmarshalText

func (f *ListField) UnmarshalText(text []byte) error

UnmarshalText decodes the input text value and appends it to the values when it's valid.

func (*ListField) Validate

func (f *ListField) Validate(_ Field) error

Validate performs the field validation.

func (*ListField) Value

func (f *ListField) Value() interface{}

Value returns the field's actuall value.

type Localized

type Localized interface {
	SetLocale(Translator)
}

Localized describes a form that can receive a translator so messages and errors can be translated.

type TextField

type TextField struct {
	*BaseField
	// contains filtered or unexported fields
}

TextField is a field with a string value.

func NewTextField

func NewTextField(name string, validators ...FieldValidator) *TextField

NewTextField returns a TextField instance.

func (*TextField) Set

func (f *TextField) Set(value interface{}) bool

Set sets the field's value.

func (*TextField) String

func (f *TextField) String() string

String returns the field's string value.

func (*TextField) UnmarshalJSON

func (f *TextField) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the input value into a string or a nil value.

func (*TextField) UnmarshalText

func (f *TextField) UnmarshalText(text []byte) error

UnmarshalText decodes the input text value into a string or nil value.

func (*TextField) Value

func (f *TextField) Value() interface{}

Value returns the field's actuall value.

type Translator

type Translator interface {
	Gettext(string, ...interface{}) string
}

Translator describes a type that implements a translation method.

type Validator

type Validator interface {
	Validate()
}

Validator describes a form that implements a custom validation.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL