Documentation ¶
Overview ¶
Package validate provides simple validation for Go.
Basic usage example:
v := validate.New() v.Required("firstName", customer.FirstName) if v.HasErrors() { fmt.Println("Had the following validation errors:") for key, errors := range v.Errors { fmt.Printf(" %s: %s", key, strings.Join(errors)) } }
All validators treat the input's zero type (empty string, 0, nil, etc.) as valid. Use the Required() validator if you want to make a parameter required.
All validators optionally accept a custom message as the last parameter:
v.Required("key", value, "you really need to set this")
The error text only includes a simple human description such as "must be set" or "must be a valid email". When adding new validations, make sure that they can be displayed properly when joined with commas. A text such as "Error: this field must be higher than 42" would look weird:
must be set, Error: this field must be higher than 42
You can set your own errors with v.Append():
if !condition { v.Append("key", "must be a valid foo") }
Some validators return the parsed value, which makes it easier both validate and get a useful value at the same time:
v := validate.New() id := v.Integer("id", c.Param("id")) if v.HasErrors() { return v } user := getUserByID(id)
Index ¶
- Variables
- type Validator
- func (v *Validator) Append(key, value string, format ...interface{})
- func (v *Validator) Boolean(key, value string, message ...string) bool
- func (v Validator) Code() int
- func (v *Validator) Date(key, value, layout string, message ...string)
- func (v *Validator) Domain(key, value string, message ...string)
- func (v *Validator) Email(key, value string, message ...string) mailaddress.Address
- func (v *Validator) Equal(o *Validator) bool
- func (v Validator) Error() string
- func (v Validator) ErrorJSON() ([]byte, error)
- func (v *Validator) ErrorOrNil() error
- func (v *Validator) Exclude(key, value string, exclude []string, message ...string)
- func (v *Validator) ExcludeInt64(key string, value int64, exclude []int64, message ...string)
- func (v *Validator) ExcludeWithSanitization(key, value string, exclude []string, message string, fs ...func(string) string)
- func (v *Validator) HasErrors() bool
- func (v *Validator) HexColor(key, value string, message ...string)
- func (v *Validator) IPv4(key, value string, message ...string) net.IP
- func (v *Validator) Include(key, value string, include []string, message ...string)
- func (v *Validator) IncludeInt64(key string, value int64, include []int64, message ...string)
- func (v *Validator) IncludeWithSanitization(key, value string, include []string, message string, fs ...func(string) string)
- func (v *Validator) Integer(key, value string, message ...string) int64
- func (v *Validator) Len(key, value string, min, max int, message ...string)
- func (v *Validator) Merge(other Validator)
- func (v *Validator) Phone(key, value string, message ...string)
- func (v *Validator) Range(key string, value, min, max int64, message ...string)
- func (v *Validator) Required(key string, value interface{}, message ...string)
- func (v *Validator) String() string
- func (v *Validator) Sub(key, subKey string, err error)
- func (v *Validator) URL(key, value string, message ...string) *url.URL
Constants ¶
This section is empty.
Variables ¶
var ( MessageRequired = "must be set" MessageDomain = "must be a valid domain" MessageURL = "must be a valid url" MessageEmail = "must be a valid email address" MessageIPv4 = "must be a valid IPv4 address" MessageHexColor = "must be a valid color code" MessageLenLonger = "must be longer than %d characters" MessageLenShorter = "must be shorter than %d characters" MessageExclude = "cannot be ‘%s’" MessageInclude = "must be one of ‘%s’" MessageInteger = "must be a whole number" MessageBool = "must be a boolean" MessageDate = "must be a date as ‘%s’" MessagePhone = "must be a valid phone number" MessageRangeHigher = "must be %d or higher" MessageRangeLower = "must be %d or lower" )
Messages for the checkers; this can be changed for i18n.
Functions ¶
This section is empty.
Types ¶
type Validator ¶
Validator hold the validation errors.
Typically you shouldn't create this directly but use the New() function.
func New ¶
func New() Validator
New makes a new Validator and ensures that it is properly initialized.
func (Validator) Code ¶
Code returns the HTTP status code for the error. Satisfies the guru.coder interface in github.com/teamwork/guru.
func (*Validator) Domain ¶
Domain validates that the domain is valid.
A domain must consist of at least two labels. So "com" or "localhost" – while technically valid domain names – are not accepted, whereas "example.com" or "me.localhost" are. For the overwhelming majority of applications this makes the most sense.
This works for internationalized domain names (IDN), either as UTF-8 characters or as punycode.
Limitation: the RFC limits domain labels to 63 bytes, but this validation accepts labels up to 63 *characters*.
func (*Validator) Email ¶
func (v *Validator) Email(key, value string, message ...string) mailaddress.Address
Email validates if this email looks like a valid email address.
func (*Validator) ErrorOrNil ¶
ErrorOrNil returns nil if there are no errors, or the Validator object if there are.
This makes it a bit more elegant to return from a function:
if v.HasErrors() { return v } return nil
Can now be:
return v.ErrorOrNil()
func (*Validator) Exclude ¶
Exclude validates that the value is not in the exclude list.
This list is matched case-insensitive.
func (*Validator) ExcludeInt64 ¶
ExcludeInt64 validates that the value is not in the exclude list.
func (*Validator) ExcludeWithSanitization ¶
func (v *Validator) ExcludeWithSanitization( key, value string, exclude []string, message string, fs ...func(string) string, )
ExcludeWithSanitization sanitizes value using fs before validating that the value is not in the exclude list.
This list is matched case-insensitive.
func (*Validator) HexColor ¶
HexColor validates if the string looks like a color as a hex triplet (e.g. #ffffff or #fff).
func (*Validator) Include ¶
Include validates that the value is in the include list.
This list is matched case-insensitive.
func (*Validator) IncludeInt64 ¶
IncludeInt64 validates that the value is in the include list.
func (*Validator) IncludeWithSanitization ¶
func (v *Validator) IncludeWithSanitization( key, value string, include []string, message string, fs ...func(string) string, )
IncludeWithSanitization sanitizes value using fs before validating that the value is in the include list.
This list is matched case-insensitive.
func (*Validator) Len ¶
Len sets the minimum and maximum length for a string in characters, not in bytes.
A maximum of 0 indicates there is no upper limit.
func (*Validator) Phone ¶
Phone checks if the string looks like a valid phone number.
There are a great amount of writing conventions for phone numbers: https://en.wikipedia.org/wiki/National_conventions_for_writing_telephone_numbers
This merely checks a field contains 5 to 20 characters "0123456789+\-() .", which is not very strict but should cover all conventions.
func (*Validator) Range ¶
Range sets the minimum and maximum value of a integer.
A maximum of 0 indicates there is no upper limit.
func (*Validator) Required ¶
Required indicates that this value must not be the type's zero value.
Currently supported types are string, int, int64, uint, and uint64. It will panic if the type is not supported.
func (*Validator) String ¶
Strings representation shows either all errors or "<no errors>" if there are no errors.
func (*Validator) Sub ¶
Sub allows to specific sub-validations.
Errors from the subvalidation are merged with the top-level one, the keys are added as "top.sub" or "top[n].sub".
If the error is not a Validator the text will be added as just the key name without subkey (i.e. the same as v.Append("key", "msg")).
For example:
v := validate.New() v.Required("name", customer.Name) // e.g. "settings.domain" v.Sub("settings", -1, customer.Settings.Validate()) // e.g. "addresses[1].city" for i, a := range customer.Addresses { a.Sub("addresses", i, c.Validate()) }