Documentation
¶
Overview ¶
This contains a copy of utf.ValidString() which also considers NULL bytes invalid.
Package zvalidate provides simple validation for Go.
See the README.markdown for an introduction.
Example ¶
package main import ( "fmt" "zgo.at/zvalidate" ) func main() { email := "martin@arp42.net" v := zvalidate.New() v.Required("email", email) m := v.Email("email", email) if v.HasErrors() { fmt.Printf("Had the following validation errors:\n%s", v) } fmt.Printf("parsed email: %s\n", m.Address) }
Output: parsed email: martin@arp42.net
Index ¶
- Variables
- func TemplateError(k string, v *Validator) template.HTML
- func TemplateHasErrors(v *Validator) bool
- 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) time.Time
- func (v *Validator) Domain(key, value string, message ...string) []string
- func (v *Validator) Email(key, value string, message ...string) mail.Address
- 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) HTML() template.HTML
- func (v *Validator) HasErrors() bool
- func (v *Validator) HexColor(key, value string, message ...string) (uint8, uint8, uint8)
- func (v *Validator) IP(key, value string, message ...string) net.IP
- 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) Integer(key, value string, message ...string) int64
- func (v *Validator) Len(key, value string, min, max int, message ...string) int
- func (v *Validator) Merge(other Validator)
- func (v *Validator) Phone(key, value string, message ...string) string
- func (v *Validator) Pop(key string) []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
- func (v *Validator) UTF8(key, value string, message ...string)
Examples ¶
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" MessageIP = "must be a valid IPv4 or IPv6 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 higher than %d" MessageRangeLower = "must be lower than %d" MessageUTF8 = "must be UTF-8" )
Messages for the validations; this can be changed for i18n.
Functions ¶
func TemplateError ¶ added in v1.2.0
TemplateError displays validation errors for the given key.
This will Pop() errors and modify the Validator in-place, so we can see if there are any "hidden" errors later on.
Example ¶
package main import ( "html/template" "os" "zgo.at/zvalidate" ) func main() { funcs := template.FuncMap{ "validate": zvalidate.TemplateError, "has_errors": zvalidate.TemplateHasErrors, } t := template.Must(template.New("").Funcs(funcs).Parse(` <input name="xxx"> {{validate "xxx" .Validate}} {{if has_errors .Validate}}Hidden: {{.Validate.HTML}}{{end}} `)) v := zvalidate.New() v.Append("xxx", "oh noes") v.Append("hidden", "sneaky") t.Execute(os.Stdout, map[string]interface{}{ "Validate": &v, }) }
Output: <input name="xxx"> <span class="err">Error: oh noes</span> Hidden: <ul class='zvalidate'> <li><strong>hidden</strong>: sneaky.</li> </ul>
func TemplateHasErrors ¶ added in v1.2.0
TemplateHasErrors reports if there are any validation errors.
This is useful because "and" evaluates all arguments, and this will error out:
{{if and .Validate .Validate.HasErrors}}
Types ¶
type Validator ¶
Validator hold the validation errors.
Typically you shouldn't create this directly but use the New() function.
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 parses a domain as individual labels.
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.
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) HTML ¶ added in v1.2.0
HTML representation of all errors, or a blank string if there are none.
func (*Validator) Include ¶
Include validates that the value is in the include list.
This list is matched case-insensitive.
func (*Validator) Len ¶
Len validates the character (rune) length of a string.
A maximum of 0 indicates there is no upper limit.
func (*Validator) Phone ¶
Phone parses a 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.
Returns the phone number with grouping/spacing characters removed.
func (*Validator) Pop ¶ added in v1.2.0
Pop an error, removing all errors for this key.
This is mostly useful when displaying errors next to forms: Pop() all the errors you want to display, and then display anything that's left with a flash message or the like. This prevents "hidden" errors.
Returns nil if there are no errors for this key.
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 validates that the value is not the type's zero value.
Currently supported types are string, int, int64, uint, uint64, bool, []string, and mail.Address. It will panic if the type is not supported.
func (*Validator) String ¶
Strings representation of all errors, or a blank string if there are none.
func (*Validator) Sub ¶
Sub adds 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 := zvalidate.New() v.Required("name", customer.Name) // key: "settings.domain" v.Sub("settings", -1, customer.Settings.Validate()) // key: "addresses[1].city" for i, a := range customer.Addresses { a.Sub("addresses", i, c.Validate()) }
func (*Validator) URL ¶
URL parses an URL.
The URL may consist of a scheme, host, path, and query parameters. Only the host is required.
The host is validated with the Domain() validation. If the scheme is not given "http" will be prepended.
func (*Validator) UTF8 ¶ added in v1.2.2
UTF8 validates that this string is valid UTF-8.
Caveat: this will consider NULL bytes *invalid* even though they're valid in UTF-8. Many tools don't accept it (e.g. PostgreSQL and SQLite), there's very rarely a reason to include them in strings, and most uses I've seen is from people trying to insert exploits. So the practical thing to do is just to reject it.