form

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: May 20, 2017 License: MIT Imports: 6 Imported by: 0

README

Humble/Form

Version GoDoc

A go package which provides functions for validating and serializing html forms. It is intended to be compiled to javascript via gopherjs and run in the browser. Form works great as a stand-alone package or in combination with other Humble packages.

Form is written in pure go. It feels like go, follows go idioms when possible, and compiles with the go tools. But it is meant to be compiled to javascript and run in the browser.

Browser Support

Form works with IE9+ (with a polyfill for typed arrays) and all other modern browsers. Form compiles to javascript via gopherjs and this is a gopherjs limitation.

Form is regularly tested with the latest versions of Firefox, Chrome, and Safari on Mac OS. Each major or minor release is tested with IE9+ and the latest versions of Firefox and Chrome on Windows.

Installation

Install form like you would any other go package:

go get github.com/go-humble/form

You will also need to install gopherjs if you don't already have it. The latest version is recommended. Install gopherjs with:

go get -u github.com/gopherjs/gopherjs

Finally, you will need to install the gopherjs dom bindings:

go get -u honnef.co/go/js/dom

Quickstart Guide

Parsing a Form

The first thing you'll want to do is create a Form object. To do this, you can get an html form element using a query selector and then pass it as an argument to the Parse function.

// Use a query selector to get the form element.
document := dom.GetWindow().Document()
formEl := document.QuerySelector("#form")
// Parse the form element and get a form.Form object in return.
f, err := form.Parse(formEl)
if err != nil {
	// Handle err.
}
Validations

You can validate the inputs in the form by using the Validate method. Validate expects an input name as an argument and returns an InputValidation object, which has chainable methods for validating a single input.

Here's an example:

// Validate the form inputs.
f.Validate("name").Required()
f.Validate("age").Required().IsInt().Greater(0).LessOrEqual(99)
// Check if there were any validation errors.
if f.HasErrors() {
	for _, err := range fmr.Errors {
		// Do something with each error.
	}
}

See the documentation on the InputValidation type for more validation methods.

Getting Input Values

You can use helper methods to get the value for an input and convert it to a go type. For example, here's how you can get the value for an input field named "age" converted to an int:

age, err := f.GetInt("age")
if err != nil {
	// Handle err.
}

See the documentation on the Form type for more helper methods.

Binding

You can bind a form to any struct by using the Bind method. Bind compares the names of the fields of the struct to the names of the form inputs. When it finds a match, it attempts to set the value of the struct field to the input value.

Suppose you had a form that looked like this:

<form>
	<input name="name" >
	<input name="age" type="number" >
</form>

And a Person struct with the following definition:

type Person struct {
	Name string
	Age  int
}

You could then bind the form to a Person using the Bind method:

person := &Person{}
if err := f.Bind(person); err != nil {
	// Handle err.
}

Bind creates a one-way, one-time binding. Changes to the form input values will not automatically update person, nor will changes to person automatically change the form input values.

Bind supports most primative types and pointers to primative types. If your struct contains a type that is not supported, you can implement the Binder or InputBinder interfaces to define custom behavior.

Testing

Form uses the karma test runner to test the code running in actual browsers.

The tests require the following additional dependencies:

Don't forget to also install the karma command line tools with npm install -g karma-cli.

You will also need to install a launcher for each browser you want to test with, as well as the browsers themselves. Typically you install a karma launcher with npm install -g karma-chrome-launcher. You can edit the config file at karma/test-mac.conf.js or create a new one (e.g. karma/test-windows.conf.js) if you want to change the browsers that are tested on.

Once you have installed all the dependencies, start karma with karma start karma/test-mac.conf.js (or your customized config file, if applicable). Once karma is running, you can keep it running in between tests.

Next you need to compile the test.go file to javascript so it can run in the browsers:

gopherjs build karma/go/form_test.go -o karma/js/form_test.js

Finally run the tests with karma run karma/test-mac.conf.js (changing the name of the config file if needed).

If you are on a unix-like operating system, you can recompile and run the tests in one go by running the provided bash script: ./karma/test.sh.

Contributing

See CONTRIBUTING.md

License

Form is licensed under the MIT License. See the LICENSE file for more information.

Documentation

Overview

Package form provides functions for validating and serializing html forms. It is intended to be compiled to javascript via gopherjs (https://github.com/gopherjs/gopherjs) and run in the browser. Form works great as a stand-alone package or in combination with other Humble packages (https://github.com/go-humble).

Version 0.0.2

For the full source code, a quickstart guide, and more information visit https://github.com/go-humble/form.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Binder

type Binder interface {
	BindForm(*Form) error
}

Binder has a single method, BindForm, which binds the values in the form to the method receiver. It can be used to override the behavior of Bind. Note that because BindForm is expected to set the value of the receiver, the receiver should always be a pointer.

type Form

type Form struct {
	Inputs map[string]*Input
	Errors []error
}

Form is a go representation of an html input form.

func Parse

func Parse(formElement dom.Element) (*Form, error)

Parse creates a and returns a Form object from the given form element.

func (*Form) Bind

func (form *Form) Bind(v interface{}) error

Bind attempts to bind the form input values to v, which must be a pointer to a struct. Bind performs a one-way, one-time binding. Changes to the form input values will not automatically update v, nor will changes to v automatically change the form input values.

The following struct field types are supported: string, []byte, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, bool, time.Time, and pointers to any of the preceding types. Bind attempts to match struct field names with input names in a case-insensitive manner. So an input with a name attribute "foo" will be assigned to the field v.Foo. Bind will simply ignore fields of v which do not match any input names and input names which do not match any fields of v. Because Bind uses reflection, only exported fields of v (those which start with a capital letter) will be affected.

If v implements Binder, form.Bind will just call v.BindForm. Similarly if any of the fields of v implement InputBinder, Bind will call BindInput on the specific field. For all other typees, Bind will attempt to do the binding using a series of conversion rules. If a field type is not supported and that field does not implement InputBinder, Bind will return an error.

Bind will return an error if the type of v is not a pointer to a struct or if there is an error arising from binding any of the individual inputs to fields.

func (*Form) GetBool

func (form *Form) GetBool(inputName string) (bool, error)

GetBool returns the value of the input identified by inputName converted to a bool. It returns an error if the input is not found or if the input value could not be converted to a bool.

func (*Form) GetFloat

func (form *Form) GetFloat(inputName string) (float64, error)

GetFloat returns the value of the input identified by inputName converted to a float. It returns an error if the input is not found or if the input value could not be converted to a float.

func (*Form) GetInt

func (form *Form) GetInt(inputName string) (int, error)

GetInt returns the value of the input identified by inputName converted to an int. It returns an error if the input is not found or if the input value could not be converted to an int.

func (*Form) GetString

func (form *Form) GetString(inputName string) (string, error)

GetString returns the value of the input identified by inputName. It returns an InputNotFoundError if there is no input with the given inputName.

func (*Form) GetTime

func (form *Form) GetTime(inputName string) (time.Time, error)

GetTime returns the value of the input identified by inputName converted to a time.Time. GetTime supports the time, date, and datetime input types and assumes the input value adheres to the rfc3339 standard (the default for form inputs). If the type of the input is anything else, it will attempt to parse it as an rfc3339 datetime. It returns an error if the input is not found or if the input value could not be converted to a time.Time.

func (*Form) GetUint

func (form *Form) GetUint(inputName string) (uint, error)

GetUint returns the value of the input identified by inputName converted to a uint. It returns an error if the input is not found or if the input value could not be converted to a uint.

func (*Form) HasErrors

func (form *Form) HasErrors() bool

HasErrors returns true if the form has at least one validation error.

func (*Form) Validate

func (form *Form) Validate(inputName string) *InputValidation

Validate returns an InputValidation object which can be used to validate a single input.

type Input

type Input struct {
	// El is the original html input element for the Input.
	El *dom.HTMLInputElement
	// Name is equal to the value of the input's name attribute.
	Name string
	// RawValue is equal to the input's value attribute.
	RawValue string
	// Type is equal to the input's type attribute. Note that this is sometimes
	// different than the type reported by type property of the HTMLInputElement
	// in the DOM API.
	Type InputType
}

Input is a go representation of an html input element.

func NewInput

func NewInput(el *dom.HTMLInputElement) *Input

NewInput creates a new Input object from the given html input element.

func (Input) Bool

func (input Input) Bool() (bool, error)

Bool converts the value of the input to a bool. For inputs with the type checkbox or radio, Bool will return true iff the input has the checked attribute. For all other input types it will attempt to parse the input value as a bool. It returns an error if the value could not be converted.

func (Input) Float

func (input Input) Float() (float64, error)

Float converts the value of the input to a float64. It returns an error if the value could not be converted.

func (Input) Int

func (input Input) Int() (int, error)

Int converts the value of the input to an int. It returns an error if the value could not be converted.

func (Input) Time

func (input Input) Time() (time.Time, error)

Time converts the value of the input to a time.Time. Time supports the time, date, and datetime input types and assumes the input value adheres to the rfc3339 standard (the default for form inputs). If the type of the input is anything else, it will attempt to parse it as an rfc3339 datetime. It returns an error if the value could not be converted.

func (Input) Uint

func (input Input) Uint() (uint, error)

Uint converts the value of the input to a uint. It returns an error if the value could not be converted.

type InputBinder

type InputBinder interface {
	BindInput(*Input) error
}

InputBinder has a single method, BindInput, which binds an input value to the receiver. It can be used to override the behavior of Bind. Typically, InputBinder should be implemented by some type which is a field of the struct passed to Bind. Note that because BindInput is expected to set the value of the receiver, the receiver should always be a pointer.

type InputNotFoundError

type InputNotFoundError struct {
	Name string
}

InputNotFoundError is returned whenever form.GetX is called with an inputName that is not found in the form inputs.

func (InputNotFoundError) Error

func (e InputNotFoundError) Error() string

Error satisifies the Error method of the error interface.

type InputType

type InputType string

InputType is a value for the type attribute of an input element.

const (
	InputDefault       InputType = ""
	InputButton        InputType = "button"
	InputCheckbox      InputType = "checkbox"
	InputColor         InputType = "color"
	InputDate          InputType = "date"
	InputDateTime      InputType = "datetime"
	InputDateTimeLocal InputType = "datetime-local"
	InputEmail         InputType = "email"
	InputFile          InputType = "file"
	InputHidden        InputType = "hidden"
	InputImage         InputType = "image"
	InputMonth         InputType = "month"
	InputNumber        InputType = "number"
	InputPassword      InputType = "password"
	InputRadio         InputType = "radio"
	InputRange         InputType = "range"
	InputReset         InputType = "reset"
	InputSearch        InputType = "search"
	InputTel           InputType = "tel"
	InputText          InputType = "text"
	InputTime          InputType = "time"
	InputURL           InputType = "url"
	InputWeek          InputType = "week"
)

type InputValidation

type InputValidation struct {
	Errors    []error
	Input     *Input
	Form      *Form
	InputName string
}

InputValidation is an object which has methods for validating an input. Such methods always return an InputValidation and are chainable. Whenever an input is invalid, a validation error is added to the corresponding Form and can be accessed via the form.HasErrors method and the form.Errors property.

func (*InputValidation) AddError

func (val *InputValidation) AddError(format string, args ...interface{})

AddError adds a validation error to the form with the given format and args. The arguments format and args work exactly like they do in fmt.Sprintf.

func (*InputValidation) Greater

func (val *InputValidation) Greater(limit int) *InputValidation

Greater adds a validation error to the form if the input is not greater than limit. Greater only works for int values.

func (*InputValidation) GreaterFloat

func (val *InputValidation) GreaterFloat(limit float64) *InputValidation

GreaterFloat adds a validation error to the form if the input is not greater than limit. GreaterFloat only works for float values.

func (*InputValidation) GreaterFloatf

func (val *InputValidation) GreaterFloatf(limit float64, format string, args ...interface{}) *InputValidation

GreaterFloatf is like GreaterFloat but allows you to specify a custom error message. The arguments format and args work exactly like they do in fmt.Sprintf.

func (*InputValidation) GreaterOrEqual

func (val *InputValidation) GreaterOrEqual(limit int) *InputValidation

GreaterOrEqual adds a validation error to the form if the input is not greater than or equal to limit. GreaterOrEqual only works for int values.

func (*InputValidation) GreaterOrEqualFloat

func (val *InputValidation) GreaterOrEqualFloat(limit float64) *InputValidation

GreaterOrEqualFloat adds a validation error to the form if the input is not greater than or equal to limit. GreaterOrEqualFloat only works for float values.

func (*InputValidation) GreaterOrEqualFloatf

func (val *InputValidation) GreaterOrEqualFloatf(limit float64, format string, args ...interface{}) *InputValidation

GreaterOrEqualFloatf is like GreaterOrEqualFloat but allows you to specify a custom error message. The arguments format and args work exactly like they do in fmt.Sprintf.

func (*InputValidation) GreaterOrEqualf

func (val *InputValidation) GreaterOrEqualf(limit int, format string, args ...interface{}) *InputValidation

GreaterOrEqualf is like GreaterOrEqual but allows you to specify a custom error message. The arguments format and args work exactly like they do in fmt.Sprintf.

func (*InputValidation) Greaterf

func (val *InputValidation) Greaterf(limit int, format string, args ...interface{}) *InputValidation

Greaterf is like Greater but allows you to specify a custom error message. The arguments format and args work exactly like they do in fmt.Sprintf.

func (*InputValidation) IsBool

func (val *InputValidation) IsBool() *InputValidation

IsBool adds a validation error to the form if the input is not convertible to a bool.

func (*InputValidation) IsBoolf

func (val *InputValidation) IsBoolf(format string, args ...interface{}) *InputValidation

IsBoolf is like IsBool but allows you to specify a custom error message. The arguments format and args work exactly like they do in fmt.Sprintf.

func (*InputValidation) IsFloat

func (val *InputValidation) IsFloat() *InputValidation

IsFloat adds a validation error to the form if the input is not convertible to a float64.

func (*InputValidation) IsFloatf

func (val *InputValidation) IsFloatf(format string, args ...interface{}) *InputValidation

IsFloatf is like IsFloat but allows you to specify a custom error message. The arguments format and args work exactly like they do in fmt.Sprintf.

func (*InputValidation) IsInt

func (val *InputValidation) IsInt() *InputValidation

IsInt adds a validation error to the form if the input is not convertible to an int.

func (*InputValidation) IsIntf

func (val *InputValidation) IsIntf(format string, args ...interface{}) *InputValidation

IsIntf is like IsInt but allows you to specify a custom error message. The arguments format and args work exactly like they do in fmt.Sprintf.

func (*InputValidation) Less

func (val *InputValidation) Less(limit int) *InputValidation

Less adds a validation error to the form if the input is not less than limit. Less only works for int values.

func (*InputValidation) LessFloat

func (val *InputValidation) LessFloat(limit float64) *InputValidation

LessFloat adds a validation error to the form if the input is not less than limit. LessFloat only works for float values.

func (*InputValidation) LessFloatf

func (val *InputValidation) LessFloatf(limit float64, format string, args ...interface{}) *InputValidation

LessFloatf is like LessFloat but allows you to specify a custom error message. The arguments format and args work exactly like they do in fmt.Sprintf.

func (*InputValidation) LessOrEqual

func (val *InputValidation) LessOrEqual(limit int) *InputValidation

LessOrEqual adds a validation error to the form if the input is not less than or equal to limit. LessOrEqual only works for int values.

func (*InputValidation) LessOrEqualFloat

func (val *InputValidation) LessOrEqualFloat(limit float64) *InputValidation

LessOrEqualFloat adds a validation error to the form if the input is not less than or equal to limit. LessOrEqualFloat only works for float values.

func (*InputValidation) LessOrEqualFloatf

func (val *InputValidation) LessOrEqualFloatf(limit float64, format string, args ...interface{}) *InputValidation

LessOrEqualFloatf is like LessOrEqualFloat but allows you to specify a custom error message. The arguments format and args work exactly like they do in fmt.Sprintf.

func (*InputValidation) LessOrEqualf

func (val *InputValidation) LessOrEqualf(limit int, format string, args ...interface{}) *InputValidation

LessOrEqualf is like LessOrEqual but allows you to specify a custom error message. The arguments format and args work exactly like they do in fmt.Sprintf.

func (*InputValidation) Lessf

func (val *InputValidation) Lessf(limit int, format string, args ...interface{}) *InputValidation

Lessf is like Less but allows you to specify a custom error message. The arguments format and args work exactly like they do in fmt.Sprintf.

func (*InputValidation) Required

func (val *InputValidation) Required() *InputValidation

Required adds a validation error to the form if the input is not included in the form or if it is an empty string.

func (*InputValidation) Requiredf

func (val *InputValidation) Requiredf(format string, args ...interface{}) *InputValidation

Requiredf is like Required but allows you to specify a custom error message. The arguments format and args work exactly like they do in fmt.Sprintf.

type ValidationError

type ValidationError struct {
	Input     *Input
	InputName string
	// contains filtered or unexported fields
}

ValidationError is returned whenever an error arises from a validation method.

func (ValidationError) Error

func (valErr ValidationError) Error() string

Error satisfies the Error method of the builtin error interface.

Jump to

Keyboard shortcuts

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