govalidator

package module
v0.0.0-...-a9d515a Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2023 License: MIT Imports: 23 Imported by: 3,932

README

govalidator

Gitter GoDoc Build Status Coverage Go Report Card GoSearch Backers on Open Collective Sponsors on Open Collective FOSSA Status

A package of validators and sanitizers for strings, structs and collections. Based on validator.js.

Installation

Make sure that Go is installed on your computer. Type the following command in your terminal:

go get github.com/asaskevich/govalidator

or you can get specified release of the package with gopkg.in:

go get gopkg.in/asaskevich/govalidator.v10

After it the package is ready to use.

Import package in your project

Add following line in your *.go file:

import "github.com/asaskevich/govalidator"

If you are unhappy to use long govalidator, you can do something like this:

import (
  valid "github.com/asaskevich/govalidator"
)
Activate behavior to require all fields have a validation tag by default

SetFieldsRequiredByDefault causes validation to fail when struct fields do not include validations or are not explicitly marked as exempt (using valid:"-" or valid:"email,optional"). A good place to activate this is a package init function or the main() function.

SetNilPtrAllowedByRequired causes validation to pass when struct fields marked by required are set to nil. This is disabled by default for consistency, but some packages that need to be able to determine between nil and zero value state can use this. If disabled, both nil and zero values cause validation errors.

import "github.com/asaskevich/govalidator"

func init() {
  govalidator.SetFieldsRequiredByDefault(true)
}

Here's some code to explain it:

// this struct definition will fail govalidator.ValidateStruct() (and the field values do not matter):
type exampleStruct struct {
  Name  string ``
  Email string `valid:"email"`
}

// this, however, will only fail when Email is empty or an invalid email address:
type exampleStruct2 struct {
  Name  string `valid:"-"`
  Email string `valid:"email"`
}

// lastly, this will only fail when Email is an invalid email address but not when it's empty:
type exampleStruct2 struct {
  Name  string `valid:"-"`
  Email string `valid:"email,optional"`
}
Recent breaking changes (see #123)
Custom validator function signature

A context was added as the second parameter, for structs this is the object being validated – this makes dependent validation possible.

import "github.com/asaskevich/govalidator"

// old signature
func(i interface{}) bool

// new signature
func(i interface{}, o interface{}) bool
Adding a custom validator

This was changed to prevent data races when accessing custom validators.

import "github.com/asaskevich/govalidator"

// before
govalidator.CustomTypeTagMap["customByteArrayValidator"] = func(i interface{}, o interface{}) bool {
  // ...
}

// after
govalidator.CustomTypeTagMap.Set("customByteArrayValidator", func(i interface{}, o interface{}) bool {
  // ...
})
List of functions:
func Abs(value float64) float64
func BlackList(str, chars string) string
func ByteLength(str string, params ...string) bool
func CamelCaseToUnderscore(str string) string
func Contains(str, substring string) bool
func Count(array []interface{}, iterator ConditionIterator) int
func Each(array []interface{}, iterator Iterator)
func ErrorByField(e error, field string) string
func ErrorsByField(e error) map[string]string
func Filter(array []interface{}, iterator ConditionIterator) []interface{}
func Find(array []interface{}, iterator ConditionIterator) interface{}
func GetLine(s string, index int) (string, error)
func GetLines(s string) []string
func HasLowerCase(str string) bool
func HasUpperCase(str string) bool
func HasWhitespace(str string) bool
func HasWhitespaceOnly(str string) bool
func InRange(value interface{}, left interface{}, right interface{}) bool
func InRangeFloat32(value, left, right float32) bool
func InRangeFloat64(value, left, right float64) bool
func InRangeInt(value, left, right interface{}) bool
func IsASCII(str string) bool
func IsAlpha(str string) bool
func IsAlphanumeric(str string) bool
func IsBase64(str string) bool
func IsByteLength(str string, min, max int) bool
func IsCIDR(str string) bool
func IsCRC32(str string) bool
func IsCRC32b(str string) bool
func IsCreditCard(str string) bool
func IsDNSName(str string) bool
func IsDataURI(str string) bool
func IsDialString(str string) bool
func IsDivisibleBy(str, num string) bool
func IsEmail(str string) bool
func IsExistingEmail(email string) bool
func IsFilePath(str string) (bool, int)
func IsFloat(str string) bool
func IsFullWidth(str string) bool
func IsHalfWidth(str string) bool
func IsHash(str string, algorithm string) bool
func IsHexadecimal(str string) bool
func IsHexcolor(str string) bool
func IsHost(str string) bool
func IsIP(str string) bool
func IsIPv4(str string) bool
func IsIPv6(str string) bool
func IsISBN(str string, version int) bool
func IsISBN10(str string) bool
func IsISBN13(str string) bool
func IsISO3166Alpha2(str string) bool
func IsISO3166Alpha3(str string) bool
func IsISO4217(str string) bool
func IsISO693Alpha2(str string) bool
func IsISO693Alpha3b(str string) bool
func IsIn(str string, params ...string) bool
func IsInRaw(str string, params ...string) bool
func IsInt(str string) bool
func IsJSON(str string) bool
func IsLatitude(str string) bool
func IsLongitude(str string) bool
func IsLowerCase(str string) bool
func IsMAC(str string) bool
func IsMD4(str string) bool
func IsMD5(str string) bool
func IsMagnetURI(str string) bool
func IsMongoID(str string) bool
func IsMultibyte(str string) bool
func IsNatural(value float64) bool
func IsNegative(value float64) bool
func IsNonNegative(value float64) bool
func IsNonPositive(value float64) bool
func IsNotNull(str string) bool
func IsNull(str string) bool
func IsNumeric(str string) bool
func IsPort(str string) bool
func IsPositive(value float64) bool
func IsPrintableASCII(str string) bool
func IsRFC3339(str string) bool
func IsRFC3339WithoutZone(str string) bool
func IsRGBcolor(str string) bool
func IsRegex(str string) bool
func IsRequestURI(rawurl string) bool
func IsRequestURL(rawurl string) bool
func IsRipeMD128(str string) bool
func IsRipeMD160(str string) bool
func IsRsaPub(str string, params ...string) bool
func IsRsaPublicKey(str string, keylen int) bool
func IsSHA1(str string) bool
func IsSHA256(str string) bool
func IsSHA384(str string) bool
func IsSHA512(str string) bool
func IsSSN(str string) bool
func IsSemver(str string) bool
func IsTiger128(str string) bool
func IsTiger160(str string) bool
func IsTiger192(str string) bool
func IsTime(str string, format string) bool
func IsType(v interface{}, params ...string) bool
func IsURL(str string) bool
func IsUTFDigit(str string) bool
func IsUTFLetter(str string) bool
func IsUTFLetterNumeric(str string) bool
func IsUTFNumeric(str string) bool
func IsUUID(str string) bool
func IsUUIDv3(str string) bool
func IsUUIDv4(str string) bool
func IsUUIDv5(str string) bool
func IsULID(str string) bool
func IsUnixTime(str string) bool
func IsUpperCase(str string) bool
func IsVariableWidth(str string) bool
func IsWhole(value float64) bool
func LeftTrim(str, chars string) string
func Map(array []interface{}, iterator ResultIterator) []interface{}
func Matches(str, pattern string) bool
func MaxStringLength(str string, params ...string) bool
func MinStringLength(str string, params ...string) bool
func NormalizeEmail(str string) (string, error)
func PadBoth(str string, padStr string, padLen int) string
func PadLeft(str string, padStr string, padLen int) string
func PadRight(str string, padStr string, padLen int) string
func PrependPathToErrors(err error, path string) error
func Range(str string, params ...string) bool
func RemoveTags(s string) string
func ReplacePattern(str, pattern, replace string) string
func Reverse(s string) string
func RightTrim(str, chars string) string
func RuneLength(str string, params ...string) bool
func SafeFileName(str string) string
func SetFieldsRequiredByDefault(value bool)
func SetNilPtrAllowedByRequired(value bool)
func Sign(value float64) float64
func StringLength(str string, params ...string) bool
func StringMatches(s string, params ...string) bool
func StripLow(str string, keepNewLines bool) string
func ToBoolean(str string) (bool, error)
func ToFloat(str string) (float64, error)
func ToInt(value interface{}) (res int64, err error)
func ToJSON(obj interface{}) (string, error)
func ToString(obj interface{}) string
func Trim(str, chars string) string
func Truncate(str string, length int, ending string) string
func TruncatingErrorf(str string, args ...interface{}) error
func UnderscoreToCamelCase(s string) string
func ValidateMap(inputMap map[string]interface{}, validationMap map[string]interface{}) (bool, error)
func ValidateStruct(s interface{}) (bool, error)
func WhiteList(str, chars string) string
type ConditionIterator
type CustomTypeValidator
type Error
func (e Error) Error() string
type Errors
func (es Errors) Error() string
func (es Errors) Errors() []error
type ISO3166Entry
type ISO693Entry
type InterfaceParamValidator
type Iterator
type ParamValidator
type ResultIterator
type UnsupportedTypeError
func (e *UnsupportedTypeError) Error() string
type Validator
Examples
IsURL
println(govalidator.IsURL(`http://user@pass:domain.com/path/page`))
IsType
println(govalidator.IsType("Bob", "string"))
println(govalidator.IsType(1, "int"))
i := 1
println(govalidator.IsType(&i, "*int"))

IsType can be used through the tag type which is essential for map validation:

type User	struct {
  Name string      `valid:"type(string)"`
  Age  int         `valid:"type(int)"`
  Meta interface{} `valid:"type(string)"`
}
result, err := govalidator.ValidateStruct(User{"Bob", 20, "meta"})
if err != nil {
	println("error: " + err.Error())
}
println(result)
ToString
type User struct {
	FirstName string
	LastName string
}

str := govalidator.ToString(&User{"John", "Juan"})
println(str)
Each, Map, Filter, Count for slices

Each iterates over the slice/array and calls Iterator for every item

data := []interface{}{1, 2, 3, 4, 5}
var fn govalidator.Iterator = func(value interface{}, index int) {
	println(value.(int))
}
govalidator.Each(data, fn)
data := []interface{}{1, 2, 3, 4, 5}
var fn govalidator.ResultIterator = func(value interface{}, index int) interface{} {
	return value.(int) * 3
}
_ = govalidator.Map(data, fn) // result = []interface{}{1, 6, 9, 12, 15}
data := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
var fn govalidator.ConditionIterator = func(value interface{}, index int) bool {
	return value.(int)%2 == 0
}
_ = govalidator.Filter(data, fn) // result = []interface{}{2, 4, 6, 8, 10}
_ = govalidator.Count(data, fn) // result = 5
ValidateStruct #2

If you want to validate structs, you can use tag valid for any field in your structure. All validators used with this field in one tag are separated by comma. If you want to skip validation, place - in your tag. If you need a validator that is not on the list below, you can add it like this:

govalidator.TagMap["duck"] = govalidator.Validator(func(str string) bool {
	return str == "duck"
})

For completely custom validators (interface-based), see below.

Here is a list of available validators for struct fields (validator - used function):

"email":              IsEmail,
"url":                IsURL,
"dialstring":         IsDialString,
"requrl":             IsRequestURL,
"requri":             IsRequestURI,
"alpha":              IsAlpha,
"utfletter":          IsUTFLetter,
"alphanum":           IsAlphanumeric,
"utfletternum":       IsUTFLetterNumeric,
"numeric":            IsNumeric,
"utfnumeric":         IsUTFNumeric,
"utfdigit":           IsUTFDigit,
"hexadecimal":        IsHexadecimal,
"hexcolor":           IsHexcolor,
"rgbcolor":           IsRGBcolor,
"lowercase":          IsLowerCase,
"uppercase":          IsUpperCase,
"int":                IsInt,
"float":              IsFloat,
"null":               IsNull,
"uuid":               IsUUID,
"uuidv3":             IsUUIDv3,
"uuidv4":             IsUUIDv4,
"uuidv5":             IsUUIDv5,
"creditcard":         IsCreditCard,
"isbn10":             IsISBN10,
"isbn13":             IsISBN13,
"json":               IsJSON,
"multibyte":          IsMultibyte,
"ascii":              IsASCII,
"printableascii":     IsPrintableASCII,
"fullwidth":          IsFullWidth,
"halfwidth":          IsHalfWidth,
"variablewidth":      IsVariableWidth,
"base64":             IsBase64,
"datauri":            IsDataURI,
"ip":                 IsIP,
"port":               IsPort,
"ipv4":               IsIPv4,
"ipv6":               IsIPv6,
"dns":                IsDNSName,
"host":               IsHost,
"mac":                IsMAC,
"latitude":           IsLatitude,
"longitude":          IsLongitude,
"ssn":                IsSSN,
"semver":             IsSemver,
"rfc3339":            IsRFC3339,
"rfc3339WithoutZone": IsRFC3339WithoutZone,
"ISO3166Alpha2":      IsISO3166Alpha2,
"ISO3166Alpha3":      IsISO3166Alpha3,
"ulid":               IsULID,

Validators with parameters

"range(min|max)": Range,
"length(min|max)": ByteLength,
"runelength(min|max)": RuneLength,
"stringlength(min|max)": StringLength,
"matches(pattern)": StringMatches,
"in(string1|string2|...|stringN)": IsIn,
"rsapub(keylength)" : IsRsaPub,
"minstringlength(int): MinStringLength,
"maxstringlength(int): MaxStringLength,

Validators with parameters for any type

"type(type)": IsType,

And here is small example of usage:

type Post struct {
	Title    string `valid:"alphanum,required"`
	Message  string `valid:"duck,ascii"`
	Message2 string `valid:"animal(dog)"`
	AuthorIP string `valid:"ipv4"`
	Date     string `valid:"-"`
}
post := &Post{
	Title:   "My Example Post",
	Message: "duck",
	Message2: "dog",
	AuthorIP: "123.234.54.3",
}

// Add your own struct validation tags
govalidator.TagMap["duck"] = govalidator.Validator(func(str string) bool {
	return str == "duck"
})

// Add your own struct validation tags with parameter
govalidator.ParamTagMap["animal"] = govalidator.ParamValidator(func(str string, params ...string) bool {
    species := params[0]
    return str == species
})
govalidator.ParamTagRegexMap["animal"] = regexp.MustCompile("^animal\\((\\w+)\\)$")

result, err := govalidator.ValidateStruct(post)
if err != nil {
	println("error: " + err.Error())
}
println(result)
ValidateMap #2

If you want to validate maps, you can use the map to be validated and a validation map that contain the same tags used in ValidateStruct, both maps have to be in the form map[string]interface{}

So here is small example of usage:

var mapTemplate = map[string]interface{}{
	"name":"required,alpha",
	"family":"required,alpha",
	"email":"required,email",
	"cell-phone":"numeric",
	"address":map[string]interface{}{
		"line1":"required,alphanum",
		"line2":"alphanum",
		"postal-code":"numeric",
	},
}

var inputMap = map[string]interface{}{
	"name":"Bob",
	"family":"Smith",
	"email":"foo@bar.baz",
	"address":map[string]interface{}{
		"line1":"",
		"line2":"",
		"postal-code":"",
	},
}

result, err := govalidator.ValidateMap(inputMap, mapTemplate)
if err != nil {
	println("error: " + err.Error())
}
println(result)
WhiteList
// Remove all characters from string ignoring characters between "a" and "z"
println(govalidator.WhiteList("a3a43a5a4a3a2a23a4a5a4a3a4", "a-z") == "aaaaaaaaaaaa")
Custom validation functions

Custom validation using your own domain specific validators is also available - here's an example of how to use it:

import "github.com/asaskevich/govalidator"

type CustomByteArray [6]byte // custom types are supported and can be validated

type StructWithCustomByteArray struct {
  ID              CustomByteArray `valid:"customByteArrayValidator,customMinLengthValidator"` // multiple custom validators are possible as well and will be evaluated in sequence
  Email           string          `valid:"email"`
  CustomMinLength int             `valid:"-"`
}

govalidator.CustomTypeTagMap.Set("customByteArrayValidator", func(i interface{}, context interface{}) bool {
  switch v := context.(type) { // you can type switch on the context interface being validated
  case StructWithCustomByteArray:
    // you can check and validate against some other field in the context,
    // return early or not validate against the context at all – your choice
  case SomeOtherType:
    // ...
  default:
    // expecting some other type? Throw/panic here or continue
  }

  switch v := i.(type) { // type switch on the struct field being validated
  case CustomByteArray:
    for _, e := range v { // this validator checks that the byte array is not empty, i.e. not all zeroes
      if e != 0 {
        return true
      }
    }
  }
  return false
})
govalidator.CustomTypeTagMap.Set("customMinLengthValidator", func(i interface{}, context interface{}) bool {
  switch v := context.(type) { // this validates a field against the value in another field, i.e. dependent validation
  case StructWithCustomByteArray:
    return len(v.ID) >= v.CustomMinLength
  }
  return false
})
Loop over Error()

By default .Error() returns all errors in a single String. To access each error you can do this:

  if err != nil {
    errs := err.(govalidator.Errors).Errors()
    for _, e := range errs {
      fmt.Println(e.Error())
    }
  }
Custom error messages

Custom error messages are supported via annotations by adding the ~ separator - here's an example of how to use it:

type Ticket struct {
  Id        int64     `json:"id"`
  FirstName string    `json:"firstname" valid:"required~First name is blank"`
}
Notes

Documentation is available here: godoc.org. Full information about code coverage is also available here: govalidator on gocover.io.

Support

If you do have a contribution to the package, feel free to create a Pull Request or an Issue.

What to contribute

If you don't know what to do, there are some features and functions that need to be done

  • Refactor code
  • Edit docs and README: spellcheck, grammar and typo check
  • Create actual list of contributors and projects that currently using this package
  • Resolve issues and bugs
  • Update actual list of functions
  • Update list of validators that available for ValidateStruct and add new
  • Implement new validators: IsFQDN, IsIMEI, IsPostalCode, IsISIN, IsISRC etc
  • Implement validation by maps
  • Implement fuzzing testing
  • Implement some struct/map/array utilities
  • Implement map/array validation
  • Implement benchmarking
  • Implement batch of examples
  • Look at forks for new features and fixes
Advice

Feel free to create what you want, but keep in mind when you implement new features:

  • Code must be clear and readable, names of variables/constants clearly describes what they are doing
  • Public functions must be documented and described in source file and added to README.md to the list of available functions
  • There are must be unit-tests for any new functions and improvements

Credits

Contributors

This project exists thanks to all the people who contribute. [Contribute].

Special thanks to contributors

Backers

Thank you to all our backers! 🙏 [Become a backer]

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

License

FOSSA Status

Documentation

Overview

Package govalidator is package of validators and sanitizers for strings, structs and collections.

Index

Examples

Constants

View Source
const (
	Email          string = "" /* 1208-byte string literal not displayed */
	CreditCard     string = "" /* 231-byte string literal not displayed */
	ISBN10         string = "^(?:[0-9]{9}X|[0-9]{10})$"
	ISBN13         string = "^(?:[0-9]{13})$"
	UUID3          string = "^[0-9a-f]{8}-[0-9a-f]{4}-3[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$"
	UUID4          string = "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"
	UUID5          string = "^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"
	UUID           string = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
	Alpha          string = "^[a-zA-Z]+$"
	Alphanumeric   string = "^[a-zA-Z0-9]+$"
	Numeric        string = "^[0-9]+$"
	Int            string = "^(?:[-+]?(?:0|[1-9][0-9]*))$"
	Float          string = "^(?:[-+]?(?:[0-9]+))?(?:\\.[0-9]*)?(?:[eE][\\+\\-]?(?:[0-9]+))?$"
	Hexadecimal    string = "^[0-9a-fA-F]+$"
	Hexcolor       string = "^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$"
	RGBcolor       string = "" /* 157-byte string literal not displayed */
	ASCII          string = "^[\x00-\x7F]+$"
	Multibyte      string = "[^\x00-\x7F]"
	FullWidth      string = "[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]"
	HalfWidth      string = "[\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]"
	Base64         string = "^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=|[A-Za-z0-9+\\/]{4})$"
	PrintableASCII string = "^[\x20-\x7E]+$"
	DataURI        string = "^data:.+\\/(.+);base64$"
	MagnetURI      string = "^magnet:\\?xt=urn:[a-zA-Z0-9]+:[a-zA-Z0-9]{32,40}&dn=.+&tr=.+$"
	Latitude       string = "^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?)$"
	Longitude      string = "^[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$"
	DNSName        string = `^([a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62}){1}(\.[a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62})*[\._]?$`
	IP             string = `` /* 659-byte string literal not displayed */
	URLSchema      string = `((ftp|tcp|udp|wss?|https?):\/\/)`
	URLUsername    string = `(\S+(:\S*)?@)`
	URLPath        string = `((\/|\?|#)[^\s]*)`
	URLPort        string = `(:(\d{1,5}))`
	URLIP          string = `([1-9]\d?|1\d\d|2[01]\d|22[0-3]|24\d|25[0-5])(\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){2}(?:\.([0-9]\d?|1\d\d|2[0-4]\d|25[0-5]))`
	URLSubdomain   string = `((www\.)|([a-zA-Z0-9]+([-_\.]?[a-zA-Z0-9])*[a-zA-Z0-9]\.[a-zA-Z0-9]+))`
	URL                   = `^` + URLSchema + `?` + URLUsername + `?` + `((` + URLIP + `|(\[` + IP + `\])|(([a-zA-Z0-9]([a-zA-Z0-9-_]+)?[a-zA-Z0-9]([-\.][a-zA-Z0-9]+)*)|(` + URLSubdomain + `?))?(([a-zA-Z\x{00a1}-\x{ffff}0-9]+-?-?)*[a-zA-Z\x{00a1}-\x{ffff}0-9]+)(?:\.([a-zA-Z\x{00a1}-\x{ffff}]{1,}))?))\.?` + URLPort + `?` + URLPath + `?$`
	SSN            string = `^\d{3}[- ]?\d{2}[- ]?\d{4}$`
	WinPath        string = `^[a-zA-Z]:\\(?:[^\\/:*?"<>|\r\n]+\\)*[^\\/:*?"<>|\r\n]*$`
	UnixPath       string = `^(/[^/\x00]*)+/?$`
	WinARPath      string = `` /* 128-byte string literal not displayed */
	UnixARPath     string = `^((\.{0,2}/)?([^/\x00]*))+/?$`
	Semver         string = "" /* 183-byte string literal not displayed */

	IMEI string = "^[0-9a-f]{14}$|^\\d{15}$|^\\d{18}$"
	IMSI string = "^\\d{14,15}$"
	E164 string = `^\+?[1-9]\d{1,14}$`
)

Basic regular expressions for validating strings

View Source
const (
	// Unknown is unresolved OS type
	Unknown = iota
	// Win is Windows type
	Win
	// Unix is *nix OS types
	Unix
)

Used by IsFilePath func

Variables

View Source
var CustomTypeTagMap = &customTypeTagMap{validators: make(map[string]CustomTypeValidator)}

CustomTypeTagMap is a map of functions that can be used as tags for ValidateStruct function. Use this to validate compound or custom types that need to be handled as a whole, e.g. `type UUID [16]byte` (this would be handled as an array of bytes).

Escape replaces <, >, & and " with HTML entities.

View Source
var ISO3166List = []ISO3166Entry{}/* 249 elements not displayed */

ISO3166List based on https://www.iso.org/obp/ui/#search/code/ Code Type "Officially Assigned Codes"

View Source
var ISO4217List = []string{}/* 181 elements not displayed */

ISO4217List is the list of ISO currency codes

View Source
var ISO693List = []ISO693Entry{}/* 184 elements not displayed */

ISO693List based on http://data.okfn.org/data/core/language-codes/r/language-codes-3b2.json

View Source
var InterfaceParamTagMap = map[string]InterfaceParamValidator{
	"type": IsType,
}

InterfaceParamTagMap is a map of functions accept variants parameters for an interface value

View Source
var InterfaceParamTagRegexMap = map[string]*regexp.Regexp{
	"type": regexp.MustCompile(`^type\((.*)\)$`),
}

InterfaceParamTagRegexMap maps interface param tags to their respective regexes.

View Source
var ParamTagMap = map[string]ParamValidator{
	"length":          ByteLength,
	"range":           Range,
	"runelength":      RuneLength,
	"stringlength":    StringLength,
	"matches":         StringMatches,
	"in":              IsInRaw,
	"rsapub":          IsRsaPub,
	"minstringlength": MinStringLength,
	"maxstringlength": MaxStringLength,
}

ParamTagMap is a map of functions accept variants parameters

View Source
var ParamTagRegexMap = map[string]*regexp.Regexp{
	"range":           regexp.MustCompile("^range\\((\\d+)\\|(\\d+)\\)$"),
	"length":          regexp.MustCompile("^length\\((\\d+)\\|(\\d+)\\)$"),
	"runelength":      regexp.MustCompile("^runelength\\((\\d+)\\|(\\d+)\\)$"),
	"stringlength":    regexp.MustCompile("^stringlength\\((\\d+)\\|(\\d+)\\)$"),
	"in":              regexp.MustCompile(`^in\((.*)\)`),
	"matches":         regexp.MustCompile(`^matches\((.+)\)$`),
	"rsapub":          regexp.MustCompile("^rsapub\\((\\d+)\\)$"),
	"minstringlength": regexp.MustCompile("^minstringlength\\((\\d+)\\)$"),
	"maxstringlength": regexp.MustCompile("^maxstringlength\\((\\d+)\\)$"),
}

ParamTagRegexMap maps param tags to their respective regexes.

View Source
var TagMap = map[string]Validator{
	"email":              IsEmail,
	"url":                IsURL,
	"dialstring":         IsDialString,
	"requrl":             IsRequestURL,
	"requri":             IsRequestURI,
	"alpha":              IsAlpha,
	"utfletter":          IsUTFLetter,
	"alphanum":           IsAlphanumeric,
	"utfletternum":       IsUTFLetterNumeric,
	"numeric":            IsNumeric,
	"utfnumeric":         IsUTFNumeric,
	"utfdigit":           IsUTFDigit,
	"hexadecimal":        IsHexadecimal,
	"hexcolor":           IsHexcolor,
	"rgbcolor":           IsRGBcolor,
	"lowercase":          IsLowerCase,
	"uppercase":          IsUpperCase,
	"int":                IsInt,
	"float":              IsFloat,
	"null":               IsNull,
	"notnull":            IsNotNull,
	"uuid":               IsUUID,
	"uuidv3":             IsUUIDv3,
	"uuidv4":             IsUUIDv4,
	"uuidv5":             IsUUIDv5,
	"creditcard":         IsCreditCard,
	"isbn10":             IsISBN10,
	"isbn13":             IsISBN13,
	"json":               IsJSON,
	"multibyte":          IsMultibyte,
	"ascii":              IsASCII,
	"printableascii":     IsPrintableASCII,
	"fullwidth":          IsFullWidth,
	"halfwidth":          IsHalfWidth,
	"variablewidth":      IsVariableWidth,
	"base64":             IsBase64,
	"datauri":            IsDataURI,
	"ip":                 IsIP,
	"port":               IsPort,
	"ipv4":               IsIPv4,
	"ipv6":               IsIPv6,
	"dns":                IsDNSName,
	"host":               IsHost,
	"mac":                IsMAC,
	"latitude":           IsLatitude,
	"longitude":          IsLongitude,
	"ssn":                IsSSN,
	"semver":             IsSemver,
	"rfc3339":            IsRFC3339,
	"rfc3339WithoutZone": IsRFC3339WithoutZone,
	"ISO3166Alpha2":      IsISO3166Alpha2,
	"ISO3166Alpha3":      IsISO3166Alpha3,
	"ISO4217":            IsISO4217,
	"IMEI":               IsIMEI,
	"ulid":               IsULID,
}

TagMap is a map of functions, that can be used as tags for ValidateStruct function.

Functions

func Abs

func Abs(value float64) float64

Abs returns absolute value of number

Example
_ = Abs(-123.3e1) // 123.3e1
_ = Abs(+0)       // 0
_ = Abs(321)      // 321
Output:

func BlackList

func BlackList(str, chars string) string

BlackList removes characters that appear in the blacklist.

func ByteLength

func ByteLength(str string, params ...string) bool

ByteLength checks string's length

func CamelCaseToUnderscore

func CamelCaseToUnderscore(str string) string

CamelCaseToUnderscore converts from camel case form to underscore separated form. Ex.: MyFunc => my_func

func Contains

func Contains(str, substring string) bool

Contains checks if the string contains the substring.

func Count

func Count(array []interface{}, iterator ConditionIterator) int

Count iterates over the slice and apply ConditionIterator to every item. Returns count of items that meets ConditionIterator.

Example
data := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
var fn ConditionIterator = func(value interface{}, index int) bool {
	return value.(int)%2 == 0
}
_ = Count(data, fn) // result = 5
Output:

func Each

func Each(array []interface{}, iterator Iterator)

Each iterates over the slice and apply Iterator to every item

Example
data := []interface{}{1, 2, 3, 4, 5}
var fn Iterator = func(value interface{}, index int) {
	println(value.(int))
}
Each(data, fn)
Output:

func ErrorByField

func ErrorByField(e error, field string) string

ErrorByField returns error for specified field of the struct validated by ValidateStruct or empty string if there are no errors or this field doesn't exists or doesn't have any errors.

func ErrorsByField

func ErrorsByField(e error) map[string]string

ErrorsByField returns map of errors of the struct validated by ValidateStruct or empty map if there are no errors.

func Every

func Every(array []interface{}, iterator ConditionIterator) bool

Every validates that every item of array corresponds to ConditionIterator. Returns boolean.

func Filter

func Filter(array []interface{}, iterator ConditionIterator) []interface{}

Filter iterates over the slice and apply ConditionIterator to every item. Returns new slice.

Example
data := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
var fn ConditionIterator = func(value interface{}, index int) bool {
	return value.(int)%2 == 0
}
_ = Filter(data, fn) // result = []interface{}{2, 4, 6, 8, 10}
Output:

func Find

func Find(array []interface{}, iterator ConditionIterator) interface{}

Find iterates over the slice and apply ConditionIterator to every item. Returns first item that meet ConditionIterator or nil otherwise.

Example
data := []interface{}{1, 2, 3, 4, 5}
var fn ConditionIterator = func(value interface{}, index int) bool {
	return value.(int) == 4
}
_ = Find(data, fn) // result = 4
Output:

func GetLine

func GetLine(s string, index int) (string, error)

GetLine returns specified line of multiline string

func GetLines

func GetLines(s string) []string

GetLines splits string by "\n" and return array of lines

func HasLowerCase

func HasLowerCase(str string) bool

HasLowerCase checks if the string contains at least 1 lowercase. Empty string is valid.

func HasUpperCase

func HasUpperCase(str string) bool

HasUpperCase checks if the string contains as least 1 uppercase. Empty string is valid.

func HasWhitespace

func HasWhitespace(str string) bool

HasWhitespace checks if the string contains any whitespace

func HasWhitespaceOnly

func HasWhitespaceOnly(str string) bool

HasWhitespaceOnly checks the string only contains whitespace

func InRange

func InRange(value interface{}, left interface{}, right interface{}) bool

InRange returns true if value lies between left and right border, generic type to handle int, float32, float64 and string. All types must the same type. False if value doesn't lie in range or if it incompatible or not comparable

Example
_ = InRange(10, 11, 20)             // false
_ = InRange(10.02, -10.124, 10.234) // true
_ = InRange("abc", "a", "cba")      // true
Output:

func InRangeFloat32

func InRangeFloat32(value, left, right float32) bool

InRangeFloat32 returns true if value lies between left and right border

Example
_ = InRangeFloat32(10.02, -10.124, 10.234) // true
_ = InRangeFloat32(10.123, 10.123, 20.431) // true
_ = InRangeFloat32(10.235, 11.124, 20.235) // false
Output:

func InRangeFloat64

func InRangeFloat64(value, left, right float64) bool

InRangeFloat64 returns true if value lies between left and right border

Example
_ = InRangeFloat64(10.02, -10.124, 10.234) // true
_ = InRangeFloat64(10.123, 10.123, 20.431) // true
_ = InRangeFloat64(10.235, 11.124, 20.235) // false
Output:

func InRangeInt

func InRangeInt(value, left, right interface{}) bool

InRangeInt returns true if value lies between left and right border

Example
_ = InRangeInt(10, -10, 10) // true
_ = InRangeInt(10, 10, 20)  // true
_ = InRangeInt(10, 11, 20)  // false
Output:

func IsASCII

func IsASCII(str string) bool

IsASCII checks if the string contains ASCII chars only. Empty string is valid.

func IsAlpha

func IsAlpha(str string) bool

IsAlpha checks if the string contains only letters (a-zA-Z). Empty string is valid.

func IsAlphanumeric

func IsAlphanumeric(str string) bool

IsAlphanumeric checks if the string contains only letters and numbers. Empty string is valid.

func IsBase64

func IsBase64(str string) bool

IsBase64 checks if a string is base64 encoded.

func IsByteLength

func IsByteLength(str string, min, max int) bool

IsByteLength checks if the string's length (in bytes) falls in a range.

func IsCIDR

func IsCIDR(str string) bool

IsCIDR checks if the string is an valid CIDR notiation (IPV4 & IPV6)

func IsCRC32

func IsCRC32(str string) bool

IsCRC32 checks is a string is a CRC32 hash. Alias for `IsHash(str, "crc32")`

func IsCRC32b

func IsCRC32b(str string) bool

IsCRC32b checks is a string is a CRC32b hash. Alias for `IsHash(str, "crc32b")`

func IsCreditCard

func IsCreditCard(str string) bool

IsCreditCard checks if the string is a credit card.

func IsDNSName

func IsDNSName(str string) bool

IsDNSName will validate the given string as a DNS name

func IsDataURI

func IsDataURI(str string) bool

IsDataURI checks if a string is base64 encoded data URI such as an image

func IsDialString

func IsDialString(str string) bool

IsDialString validates the given string for usage with the various Dial() functions

func IsDivisibleBy

func IsDivisibleBy(str, num string) bool

IsDivisibleBy checks if the string is a number that's divisible by another. If second argument is not valid integer or zero, it's return false. Otherwise, if first argument is not valid integer or zero, it's return true (Invalid string converts to zero).

Example

This small example illustrate how to work with IsDivisibleBy function.

println("1024 is divisible by 64: ", IsDivisibleBy("1024", "64"))
Output:

func IsE164

func IsE164(str string) bool

func IsEmail

func IsEmail(str string) bool

IsEmail checks if the string is an email.

func IsExistingEmail

func IsExistingEmail(email string) bool

IsExistingEmail checks if the string is an email of existing domain

func IsFilePath

func IsFilePath(str string) (bool, int)

IsFilePath checks is a string is Win or Unix file path and returns it's type.

func IsFloat

func IsFloat(str string) bool

IsFloat checks if the string is a float.

func IsFullWidth

func IsFullWidth(str string) bool

IsFullWidth checks if the string contains any full-width chars. Empty string is valid.

func IsHalfWidth

func IsHalfWidth(str string) bool

IsHalfWidth checks if the string contains any half-width chars. Empty string is valid.

func IsHash

func IsHash(str string, algorithm string) bool

IsHash checks if a string is a hash of type algorithm. Algorithm is one of ['md4', 'md5', 'sha1', 'sha256', 'sha384', 'sha512', 'ripemd128', 'ripemd160', 'tiger128', 'tiger160', 'tiger192', 'crc32', 'crc32b']

func IsHexadecimal

func IsHexadecimal(str string) bool

IsHexadecimal checks if the string is a hexadecimal number.

func IsHexcolor

func IsHexcolor(str string) bool

IsHexcolor checks if the string is a hexadecimal color.

func IsHost

func IsHost(str string) bool

IsHost checks if the string is a valid IP (both v4 and v6) or a valid DNS name

func IsIMEI

func IsIMEI(str string) bool

IsIMEI checks if a string is valid IMEI

func IsIMSI

func IsIMSI(str string) bool

IsIMSI checks if a string is valid IMSI

func IsIP

func IsIP(str string) bool

IsIP checks if a string is either IP version 4 or 6. Alias for `net.ParseIP`

func IsIPv4

func IsIPv4(str string) bool

IsIPv4 checks if the string is an IP version 4.

func IsIPv6

func IsIPv6(str string) bool

IsIPv6 checks if the string is an IP version 6.

func IsISBN

func IsISBN(str string, version int) bool

IsISBN checks if the string is an ISBN (version 10 or 13). If version value is not equal to 10 or 13, it will be checks both variants.

func IsISBN10

func IsISBN10(str string) bool

IsISBN10 checks if the string is an ISBN version 10.

func IsISBN13

func IsISBN13(str string) bool

IsISBN13 checks if the string is an ISBN version 13.

func IsISO3166Alpha2

func IsISO3166Alpha2(str string) bool

IsISO3166Alpha2 checks if a string is valid two-letter country code

func IsISO3166Alpha3

func IsISO3166Alpha3(str string) bool

IsISO3166Alpha3 checks if a string is valid three-letter country code

func IsISO4217

func IsISO4217(str string) bool

IsISO4217 checks if string is valid ISO currency code

func IsISO693Alpha2

func IsISO693Alpha2(str string) bool

IsISO693Alpha2 checks if a string is valid two-letter language code

func IsISO693Alpha3b

func IsISO693Alpha3b(str string) bool

IsISO693Alpha3b checks if a string is valid three-letter language code

func IsIn

func IsIn(str string, params ...string) bool

IsIn checks if string str is a member of the set of strings params

func IsInRaw

func IsInRaw(str string, params ...string) bool

IsInRaw checks if string is in list of allowed values

func IsInt

func IsInt(str string) bool

IsInt checks if the string is an integer. Empty string is valid.

func IsJSON

func IsJSON(str string) bool

IsJSON checks if the string is valid JSON (note: uses json.Unmarshal).

func IsLatitude

func IsLatitude(str string) bool

IsLatitude checks if a string is valid latitude.

func IsLongitude

func IsLongitude(str string) bool

IsLongitude checks if a string is valid longitude.

func IsLowerCase

func IsLowerCase(str string) bool

IsLowerCase checks if the string is lowercase. Empty string is valid.

func IsMAC

func IsMAC(str string) bool

IsMAC checks if a string is valid MAC address. Possible MAC formats: 01:23:45:67:89:ab 01:23:45:67:89:ab:cd:ef 01-23-45-67-89-ab 01-23-45-67-89-ab-cd-ef 0123.4567.89ab 0123.4567.89ab.cdef

func IsMD4

func IsMD4(str string) bool

IsMD4 checks is a string is a MD4 hash. Alias for `IsHash(str, "md4")`

func IsMD5

func IsMD5(str string) bool

IsMD5 checks is a string is a MD5 hash. Alias for `IsHash(str, "md5")`

func IsMagnetURI

func IsMagnetURI(str string) bool

IsMagnetURI checks if a string is valid magnet URI

func IsMongoID

func IsMongoID(str string) bool

IsMongoID checks if the string is a valid hex-encoded representation of a MongoDB ObjectId.

func IsMultibyte

func IsMultibyte(str string) bool

IsMultibyte checks if the string contains one or more multibyte chars. Empty string is valid.

func IsNatural

func IsNatural(value float64) bool

IsNatural returns true if value is natural number (positive and whole)

Example
_ = IsNatural(1.123) // false
_ = IsNatural(1.0)   // true
_ = IsNatural(-10)   // false
Output:

func IsNegative

func IsNegative(value float64) bool

IsNegative returns true if value < 0

Example
_ = IsNegative(-123) // true
_ = IsNegative(0)    // false
_ = IsNegative(123)  // false
Output:

func IsNonNegative

func IsNonNegative(value float64) bool

IsNonNegative returns true if value >= 0

Example
_ = IsNonNegative(-123) // false
_ = IsNonNegative(0)    // true
_ = IsNonNegative(123)  // true
Output:

func IsNonPositive

func IsNonPositive(value float64) bool

IsNonPositive returns true if value <= 0

Example
_ = IsNonPositive(-123) // true
_ = IsNonPositive(0)    // true
_ = IsNonPositive(123)  // false
Output:

func IsNotNull

func IsNotNull(str string) bool

IsNotNull checks if the string is not null.

func IsNull

func IsNull(str string) bool

IsNull checks if the string is null.

func IsNumeric

func IsNumeric(str string) bool

IsNumeric checks if the string contains only numbers. Empty string is valid.

func IsPort

func IsPort(str string) bool

IsPort checks if a string represents a valid port

func IsPositive

func IsPositive(value float64) bool

IsPositive returns true if value > 0

Example
_ = IsPositive(-123) // false
_ = IsPositive(0)    // false
_ = IsPositive(123)  // true
Output:

func IsPrintableASCII

func IsPrintableASCII(str string) bool

IsPrintableASCII checks if the string contains printable ASCII chars only. Empty string is valid.

func IsRFC3339

func IsRFC3339(str string) bool

IsRFC3339 checks if string is valid timestamp value according to RFC3339

func IsRFC3339WithoutZone

func IsRFC3339WithoutZone(str string) bool

IsRFC3339WithoutZone checks if string is valid timestamp value according to RFC3339 which excludes the timezone.

func IsRGBcolor

func IsRGBcolor(str string) bool

IsRGBcolor checks if the string is a valid RGB color in form rgb(RRR, GGG, BBB).

func IsRegex

func IsRegex(str string) bool

IsRegex checks if a give string is a valid regex with RE2 syntax or not

func IsRequestURI

func IsRequestURI(rawurl string) bool

IsRequestURI checks if the string rawurl, assuming it was received in an HTTP request, is an absolute URI or an absolute path.

func IsRequestURL

func IsRequestURL(rawurl string) bool

IsRequestURL checks if the string rawurl, assuming it was received in an HTTP request, is a valid URL confirm to RFC 3986

func IsRipeMD128

func IsRipeMD128(str string) bool

IsRipeMD128 checks is a string is a RipeMD128 hash. Alias for `IsHash(str, "ripemd128")`

func IsRipeMD160

func IsRipeMD160(str string) bool

IsRipeMD160 checks is a string is a RipeMD160 hash. Alias for `IsHash(str, "ripemd160")`

func IsRsaPub

func IsRsaPub(str string, params ...string) bool

IsRsaPub checks whether string is valid RSA key Alias for IsRsaPublicKey

func IsRsaPublicKey

func IsRsaPublicKey(str string, keylen int) bool

IsRsaPublicKey checks if a string is valid public key with provided length

func IsSHA1

func IsSHA1(str string) bool

IsSHA1 checks is a string is a SHA-1 hash. Alias for `IsHash(str, "sha1")`

func IsSHA256

func IsSHA256(str string) bool

IsSHA256 checks is a string is a SHA256 hash. Alias for `IsHash(str, "sha256")`

func IsSHA3224

func IsSHA3224(str string) bool

IsSHA3224 checks is a string is a SHA3-224 hash. Alias for `IsHash(str, "sha3-224")`

func IsSHA3256

func IsSHA3256(str string) bool

IsSHA3256 checks is a string is a SHA3-256 hash. Alias for `IsHash(str, "sha3-256")`

func IsSHA3384

func IsSHA3384(str string) bool

IsSHA3384 checks is a string is a SHA3-384 hash. Alias for `IsHash(str, "sha3-384")`

func IsSHA3512

func IsSHA3512(str string) bool

IsSHA3512 checks is a string is a SHA3-512 hash. Alias for `IsHash(str, "sha3-512")`

func IsSHA384

func IsSHA384(str string) bool

IsSHA384 checks is a string is a SHA384 hash. Alias for `IsHash(str, "sha384")`

func IsSHA512

func IsSHA512(str string) bool

IsSHA512 checks is a string is a SHA512 hash. Alias for `IsHash(str, "sha512")`

func IsSSN

func IsSSN(str string) bool

IsSSN will validate the given string as a U.S. Social Security Number

func IsSemver

func IsSemver(str string) bool

IsSemver checks if string is valid semantic version

func IsTiger128

func IsTiger128(str string) bool

IsTiger128 checks is a string is a Tiger128 hash. Alias for `IsHash(str, "tiger128")`

func IsTiger160

func IsTiger160(str string) bool

IsTiger160 checks is a string is a Tiger160 hash. Alias for `IsHash(str, "tiger160")`

func IsTiger192

func IsTiger192(str string) bool

IsTiger192 checks is a string is a Tiger192 hash. Alias for `IsHash(str, "tiger192")`

func IsTime

func IsTime(str string, format string) bool

IsTime checks if string is valid according to given format

func IsType

func IsType(v interface{}, params ...string) bool

IsType checks if interface is of some type

func IsULID

func IsULID(str string) bool

IsULID checks if the string is a ULID.

Implementation got from:

https://github.com/oklog/ulid (Apache-2.0 License)

func IsURL

func IsURL(str string) bool

IsURL checks if the string is an URL.

func IsUTFDigit

func IsUTFDigit(str string) bool

IsUTFDigit checks if the string contains only unicode radix-10 decimal digits. Empty string is valid.

func IsUTFLetter

func IsUTFLetter(str string) bool

IsUTFLetter checks if the string contains only unicode letter characters. Similar to IsAlpha but for all languages. Empty string is valid.

func IsUTFLetterNumeric

func IsUTFLetterNumeric(str string) bool

IsUTFLetterNumeric checks if the string contains only unicode letters and numbers. Empty string is valid.

func IsUTFNumeric

func IsUTFNumeric(str string) bool

IsUTFNumeric checks if the string contains only unicode numbers of any kind. Numbers can be 0-9 but also Fractions ¾,Roman Ⅸ and Hangzhou 〩. Empty string is valid.

func IsUUID

func IsUUID(str string) bool

IsUUID checks if the string is a UUID (version 3, 4 or 5).

func IsUUIDv3

func IsUUIDv3(str string) bool

IsUUIDv3 checks if the string is a UUID version 3.

func IsUUIDv4

func IsUUIDv4(str string) bool

IsUUIDv4 checks if the string is a UUID version 4.

func IsUUIDv5

func IsUUIDv5(str string) bool

IsUUIDv5 checks if the string is a UUID version 5.

func IsUnixFilePath

func IsUnixFilePath(str string) bool

IsUnixFilePath checks both relative & absolute paths in Unix

func IsUnixTime

func IsUnixTime(str string) bool

IsUnixTime checks if string is valid unix timestamp value

func IsUpperCase

func IsUpperCase(str string) bool

IsUpperCase checks if the string is uppercase. Empty string is valid.

func IsVariableWidth

func IsVariableWidth(str string) bool

IsVariableWidth checks if the string contains a mixture of full and half-width chars. Empty string is valid.

func IsWhole

func IsWhole(value float64) bool

IsWhole returns true if value is whole number

Example
_ = IsWhole(1.123) // false
_ = IsWhole(1.0)   // true
_ = IsWhole(10)    // true
Output:

func IsWinFilePath

func IsWinFilePath(str string) bool

IsWinFilePath checks both relative & absolute paths in Windows

func LeftTrim

func LeftTrim(str, chars string) string

LeftTrim trims characters from the left side of the input. If second argument is empty, it will remove leading spaces.

func Map

func Map(array []interface{}, iterator ResultIterator) []interface{}

Map iterates over the slice and apply ResultIterator to every item. Returns new slice as a result.

Example
data := []interface{}{1, 2, 3, 4, 5}
var fn ResultIterator = func(value interface{}, index int) interface{} {
	return value.(int) * 3
}
_ = Map(data, fn) // result = []interface{}{1, 6, 9, 12, 15}
Output:

func Matches

func Matches(str, pattern string) bool

Matches checks if string matches the pattern (pattern is regular expression) In case of error return false

func MaxStringLength

func MaxStringLength(str string, params ...string) bool

MaxStringLength checks string's maximum length (including multi byte strings)

func MinStringLength

func MinStringLength(str string, params ...string) bool

MinStringLength checks string's minimum length (including multi byte strings)

func NormalizeEmail

func NormalizeEmail(str string) (string, error)

NormalizeEmail canonicalize an email address. The local part of the email address is lowercased for all domains; the hostname is always lowercased and the local part of the email address is always lowercased for hosts that are known to be case-insensitive (currently only GMail). Normalization follows special rules for known providers: currently, GMail addresses have dots removed in the local part and are stripped of tags (e.g. some.one+tag@gmail.com becomes someone@gmail.com) and all @googlemail.com addresses are normalized to @gmail.com.

func PadBoth

func PadBoth(str string, padStr string, padLen int) string

PadBoth pads both sides of a string if size of string is less then indicated pad length

func PadLeft

func PadLeft(str string, padStr string, padLen int) string

PadLeft pads left side of a string if size of string is less then indicated pad length

func PadRight

func PadRight(str string, padStr string, padLen int) string

PadRight pads right side of a string if size of string is less then indicated pad length

func Range

func Range(str string, params ...string) bool

Range checks string's length

func Reduce

func Reduce(array []interface{}, iterator ReduceIterator, initialValue interface{}) interface{}

Reduce boils down a list of values into a single value by ReduceIterator

func RemoveTags

func RemoveTags(s string) string

RemoveTags removes all tags from HTML string

func ReplacePattern

func ReplacePattern(str, pattern, replace string) string

ReplacePattern replaces regular expression pattern in string

Example
// Replace in "http123123ftp://git534543hub.comio" following (pattern "(ftp|io|[0-9]+)"):
// - Sequence "ftp".
// - Sequence "io".
// - Sequence of digits.
// with empty string.
println(ReplacePattern("http123123ftp://git534543hub.comio", "(ftp|io|[0-9]+)", "") == "http://github.com")
Output:

func Reverse

func Reverse(s string) string

Reverse returns reversed string

func RightTrim

func RightTrim(str, chars string) string

RightTrim trims characters from the right side of the input. If second argument is empty, it will remove trailing spaces.

func RuneLength

func RuneLength(str string, params ...string) bool

RuneLength checks string's length Alias for StringLength

func SafeFileName

func SafeFileName(str string) string

SafeFileName returns safe string that can be used in file names

func SetFieldsRequiredByDefault

func SetFieldsRequiredByDefault(value bool)

SetFieldsRequiredByDefault causes validation to fail when struct fields do not include validations or are not explicitly marked as exempt (using `valid:"-"` or `valid:"email,optional"`). This struct definition will fail govalidator.ValidateStruct() (and the field values do not matter):

type exampleStruct struct {
    Name  string ``
    Email string `valid:"email"`

This, however, will only fail when Email is empty or an invalid email address:

type exampleStruct2 struct {
    Name  string `valid:"-"`
    Email string `valid:"email"`

Lastly, this will only fail when Email is an invalid email address but not when it's empty:

type exampleStruct2 struct {
    Name  string `valid:"-"`
    Email string `valid:"email,optional"`

func SetNilPtrAllowedByRequired

func SetNilPtrAllowedByRequired(value bool)

SetNilPtrAllowedByRequired causes validation to pass for nil ptrs when a field is set to required. The validation will still reject ptr fields in their zero value state. Example with this enabled:

type exampleStruct struct {
    Name  *string `valid:"required"`

With `Name` set to "", this will be considered invalid input and will cause a validation error. With `Name` set to nil, this will be considered valid by validation. By default this is disabled.

func Sign

func Sign(value float64) float64

Sign returns signum of number: 1 in case of value > 0, -1 in case of value < 0, 0 otherwise

Example
_ = Sign(-123) // -1
_ = Sign(123)  // 1
_ = Sign(0)    // 0
Output:

func Some

func Some(array []interface{}, iterator ConditionIterator) bool

Some validates that any item of array corresponds to ConditionIterator. Returns boolean.

func StringLength

func StringLength(str string, params ...string) bool

StringLength checks string's length (including multi byte strings)

func StringMatches

func StringMatches(s string, params ...string) bool

StringMatches checks if a string matches a given pattern.

func StripLow

func StripLow(str string, keepNewLines bool) string

StripLow removes characters with a numerical value < 32 and 127, mostly control characters. If keep_new_lines is true, newline characters are preserved (\n and \r, hex 0xA and 0xD).

func ToBoolean

func ToBoolean(str string) (bool, error)

ToBoolean convert the input string to a boolean.

Example
// Returns the boolean value represented by the string.
// It accepts 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False.
// Any other value returns an error.
_, _ = ToBoolean("false")  // false, nil
_, _ = ToBoolean("T")      // true, nil
_, _ = ToBoolean("123123") // false, error
Output:

func ToFloat

func ToFloat(value interface{}) (res float64, err error)

ToFloat convert the input string to a float, or 0.0 if the input is not a float.

Example
_, _ = ToFloat("-124.2e123") // -124.2e123, nil
_, _ = ToFloat("false")      // 0, error
Output:

func ToInt

func ToInt(value interface{}) (res int64, err error)

ToInt convert the input string or any int type to an integer type 64, or 0 if the input is not an integer.

Example
_, _ = ToInt(1.0)     // 1, nil
_, _ = ToInt("-124")  // -124, nil
_, _ = ToInt("false") // 0, error
Output:

func ToJSON

func ToJSON(obj interface{}) (string, error)

ToJSON convert the input to a valid JSON string

Example
_, _ = ToJSON([]int{1, 2, 3})          // [1, 2, 3]
_, _ = ToJSON(map[int]int{1: 2, 2: 3}) // { "1": 2, "2": 3 }
_, _ = ToJSON(func() {})               // error
Output:

func ToString

func ToString(obj interface{}) string

ToString convert the input to a string.

Example
_ = ToString(new(interface{}))        // 0xc000090200
_ = ToString(time.Second + time.Hour) // 1h1s
_ = ToString(123)                     // 123
Output:

func Trim

func Trim(str, chars string) string

Trim trims characters from both sides of the input. If second argument is empty, it will remove spaces.

Example
// Remove from left and right spaces and "\r", "\n", "\t" characters
println(Trim("   \r\r\ntext\r   \t\n", "") == "text")
// Remove from left and right characters that are between "1" and "8".
// "1-8" is like full list "12345678".
println(Trim("1234567890987654321", "1-8") == "909")
Output:

func Truncate

func Truncate(str string, length int, ending string) string

Truncate a string to the closest length without breaking words.

func TruncatingErrorf

func TruncatingErrorf(str string, args ...interface{}) error

TruncatingErrorf removes extra args from fmt.Errorf if not formatted in the str object

func UnderscoreToCamelCase

func UnderscoreToCamelCase(s string) string

UnderscoreToCamelCase converts from underscore separated form to camel case form. Ex.: my_func => MyFunc

func ValidateArray

func ValidateArray(array []interface{}, iterator ConditionIterator) bool

ValidateArray performs validation according to condition iterator that validates every element of the array

func ValidateMap

func ValidateMap(s map[string]interface{}, m map[string]interface{}) (bool, error)

ValidateMap use validation map for fields. result will be equal to `false` if there are any errors. s is the map containing the data to be validated. m is the validation map in the form:

map[string]interface{}{"name":"required,alpha","address":map[string]interface{}{"line1":"required,alphanum"}}

func ValidateMapAsync

func ValidateMapAsync(s map[string]interface{}, m map[string]interface{}) (<-chan bool, <-chan error)

ValidateMapAsync performs async validation of the map and returns results through the channels

func ValidateStruct

func ValidateStruct(s interface{}) (bool, error)

ValidateStruct use tags for fields. result will be equal to `false` if there are any errors. todo currently there is no guarantee that errors will be returned in predictable order (tests may to fail)

Example
type Post struct {
	Title    string `valid:"alphanum,required"`
	Message  string `valid:"duck,ascii"`
	AuthorIP string `valid:"ipv4"`
}
post := &Post{"My Example Post", "duck", "123.234.54.3"}

//Add your own struct validation tags
TagMap["duck"] = Validator(func(str string) bool {
	return str == "duck"
})

result, err := ValidateStruct(post)
if err != nil {
	println("error: " + err.Error())
}
println(result)
Output:

func ValidateStructAsync

func ValidateStructAsync(s interface{}) (<-chan bool, <-chan error)

ValidateStructAsync performs async validation of the struct and returns results through the channels

func WhiteList

func WhiteList(str, chars string) string

WhiteList removes characters that do not appear in the whitelist.

Example
// Remove all characters from string ignoring characters between "a" and "z"
println(WhiteList("a3a43a5a4a3a2a23a4a5a4a3a4", "a-z") == "aaaaaaaaaaaa")
Output:

Types

type ConditionIterator

type ConditionIterator func(interface{}, int) bool

ConditionIterator is the function that accepts element of slice/array and its index and returns boolean

type CustomTypeValidator

type CustomTypeValidator func(i interface{}, o interface{}) bool

CustomTypeValidator is a wrapper for validator functions that returns bool and accepts any type. The second parameter should be the context (in the case of validating a struct: the whole object being validated).

type Error

type Error struct {
	Name                     string
	Err                      error
	CustomErrorMessageExists bool

	// Validator indicates the name of the validator that failed
	Validator string
	Path      []string
}

Error encapsulates a name, an error and whether there's a custom error message or not.

func (Error) Error

func (e Error) Error() string

type Errors

type Errors []error

Errors is an array of multiple errors and conforms to the error interface.

func (Errors) Error

func (es Errors) Error() string

func (Errors) Errors

func (es Errors) Errors() []error

Errors returns itself.

type ISO3166Entry

type ISO3166Entry struct {
	EnglishShortName string
	FrenchShortName  string
	Alpha2Code       string
	Alpha3Code       string
	Numeric          string
}

ISO3166Entry stores country codes

type ISO693Entry

type ISO693Entry struct {
	Alpha3bCode string
	Alpha2Code  string
	English     string
}

ISO693Entry stores ISO language codes

type InterfaceParamValidator

type InterfaceParamValidator func(in interface{}, params ...string) bool

InterfaceParamValidator is a wrapper for functions that accept variants parameters for an interface value

type Iterator

type Iterator func(interface{}, int)

Iterator is the function that accepts element of slice/array and its index

type ParamValidator

type ParamValidator func(str string, params ...string) bool

ParamValidator is a wrapper for validator functions that accept additional parameters.

type ReduceIterator

type ReduceIterator func(interface{}, interface{}) interface{}

ReduceIterator is the function that accepts two element of slice/array and returns result of merging those values

type ResultIterator

type ResultIterator func(interface{}, int) interface{}

ResultIterator is the function that accepts element of slice/array and its index and returns any result

type UnsupportedTypeError

type UnsupportedTypeError struct {
	Type reflect.Type
}

UnsupportedTypeError is a wrapper for reflect.Type

func (*UnsupportedTypeError) Error

func (e *UnsupportedTypeError) Error() string

Error returns string equivalent for reflect.Type

type Validator

type Validator func(str string) bool

Validator is a wrapper for a validator function that returns bool and accepts string.

Jump to

Keyboard shortcuts

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