govalidator

package
v0.0.0-...-e7b3743 Latest Latest
Warning

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

Go to latest
Published: Feb 9, 2020 License: MIT, MIT Imports: 15 Imported by: 0

README

govalidator

Gitter GoDoc Coverage Status views wercker status Build 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

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 unhappy to use long govalidator, you can do something like this:

import (
	valid "github.com/asaskevich/govalidator"
)
List of functions:
func Abs(value float64) float64
func BlackList(str, chars string) string
func ByteLength(str string, params ...string) bool
func StringLength(str string, params ...string) bool
func StringMatches(s 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 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 InRange(value, left, right float64) 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 IsCreditCard(str string) bool
func IsDataURI(str string) bool
func IsDialString(str string) bool
func IsDNSName(str string) bool
func IsDivisibleBy(str, num string) bool
func IsEmail(str string) bool
func IsFilePath(str string) (bool, int)
func IsFloat(str string) bool
func IsFullWidth(str string) bool
func IsHalfWidth(str string) bool
func IsHexadecimal(str string) bool
func IsHexcolor(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 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 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 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 IsRGBcolor(str string) bool
func IsRequestURI(rawurl string) bool
func IsRequestURL(rawurl string) bool
func IsSSN(str string) bool
func IsSemver(str 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 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 NormalizeEmail(str string) (string, error)
func RemoveTags(s string) string
func ReplacePattern(str, pattern, replace string) string
func Reverse(s string) string
func RightTrim(str, chars string) string
func SafeFileName(str string) string
func Sign(value float64) float64
func StripLow(str string, keepNewLines bool) string
func ToBoolean(str string) (bool, error)
func ToFloat(str string) (float64, error)
func ToInt(str string) (int64, 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 UnderscoreToCamelCase(s string) string
func ValidateStruct(s interface{}) (bool, error)
func WhiteList(str, chars string) string
type ConditionIterator
type Error
func (e Error) Error() string
type Errors
func (es Errors) Error() string
type ISO3166Entry
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`))
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"
})

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

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

Validators with parameters

"length(min|max)": ByteLength,
"matches(pattern)": StringMatches,

And here is small example of usage:

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

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

result, err := govalidator.ValidateStruct(post)
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")
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 for the package feel free to put up a Pull Request or open Issue.

Special thanks to contributors

Bitdeli Badge

Documentation

Overview

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

Index

Examples

Constants

View Source
const (
	Email          string = "" /* 1212-byte string literal not displayed */
	CreditCard     string = "" /* 151-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$"
	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_-]{1,62}){1}(.[a-zA-Z0-9]{1}[a-zA-Z0-9_-]{1,62})*$`
	URL            string = `` /* 322-byte string literal not displayed */
	SSN            string = `^\d{3}[- ]?\d{2}[- ]?\d{4}$`
	WinPath        string = `^[a-zA-Z]:\\(?:[^\\/:*?"<>|\r\n]+\\)*[^\\/:*?"<>|\r\n]*$`
	UnixPath       string = `^((?:\/[a-zA-Z0-9\.\:]+(?:_[a-zA-Z0-9\:\.]+)*(?:\-[\:a-zA-Z0-9\.]+)*)+\/?)$`
	Semver         string = "" /* 183-byte string literal not displayed */

)

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 = 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 replace <, >, & 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 ParamTagMap = map[string]ParamValidator{
	"length":       ByteLength,
	"stringlength": StringLength,
	"matches":      StringMatches,
}

ParamTagMap is a map of functions accept variants parameters

View Source
var ParamTagRegexMap = map[string]*regexp.Regexp{
	"length":       regexp.MustCompile("^length\\((\\d+)\\|(\\d+)\\)$"),
	"stringlength": regexp.MustCompile("^stringlength\\((\\d+)\\|(\\d+)\\)$"),
	"matches":      regexp.MustCompile(`matches\(([^)]+)\)`),
}
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,
	"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,
	"mac":            IsMAC,
	"latitude":       IsLatitude,
	"longitude":      IsLongitude,
	"ssn":            IsSSN,
	"semver":         IsSemver,
}

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

func BlackList

func BlackList(str, chars string) string

BlackList remove characters that appear in the blacklist.

func ByteLength

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

ByteLength check 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 check 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 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.

func GetLine

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

GetLine return specified line of multiline string

func GetLines

func GetLines(s string) []string

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

func InRange

func InRange(value, left, right float64) bool

InRange returns true if value lies between left and right border

func IsASCII

func IsASCII(str string) bool

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

func IsAlpha

func IsAlpha(str string) bool

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

func IsAlphanumeric

func IsAlphanumeric(str string) bool

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

func IsBase64

func IsBase64(str string) bool

IsBase64 check if a string is base64 encoded.

func IsByteLength

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

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

func IsCreditCard

func IsCreditCard(str string) bool

IsCreditCard check 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 check 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 IsEmail

func IsEmail(str string) bool

IsEmail check if the string is an email.

func IsFilePath

func IsFilePath(str string) (bool, int)

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

func IsFloat

func IsFloat(str string) bool

IsFloat check if the string is a float.

func IsFullWidth

func IsFullWidth(str string) bool

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

func IsHalfWidth

func IsHalfWidth(str string) bool

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

func IsHexadecimal

func IsHexadecimal(str string) bool

IsHexadecimal check if the string is a hexadecimal number.

func IsHexcolor

func IsHexcolor(str string) bool

IsHexcolor check if the string is a hexadecimal color.

func IsIP

func IsIP(str string) bool

IsIP checks if a string is either IP version 4 or 6.

func IsIPv4

func IsIPv4(str string) bool

IsIPv4 check if the string is an IP version 4.

func IsIPv6

func IsIPv6(str string) bool

IsIPv6 check if the string is an IP version 6.

func IsISBN

func IsISBN(str string, version int) bool

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

func IsISBN10

func IsISBN10(str string) bool

IsISBN10 check if the string is an ISBN version 10.

func IsISBN13

func IsISBN13(str string) bool

IsISBN13 check 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 IsInt

func IsInt(str string) bool

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

func IsJSON

func IsJSON(str string) bool

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

func IsLatitude

func IsLatitude(str string) bool

IsLatitude check if a string is valid latitude.

func IsLongitude

func IsLongitude(str string) bool

IsLongitude check if a string is valid longitude.

func IsLowerCase

func IsLowerCase(str string) bool

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

func IsMAC

func IsMAC(str string) bool

IsMAC check 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 IsMongoID

func IsMongoID(str string) bool

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

func IsMultibyte

func IsMultibyte(str string) bool

IsMultibyte check 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)

func IsNegative

func IsNegative(value float64) bool

IsNegative returns true if value < 0

func IsNonNegative

func IsNonNegative(value float64) bool

IsNonNegative returns true if value >= 0

func IsNonPositive

func IsNonPositive(value float64) bool

IsNonPositive returns true if value <= 0

func IsNull

func IsNull(str string) bool

IsNull check if the string is null.

func IsNumeric

func IsNumeric(str string) bool

IsNumeric check 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

func IsPrintableASCII

func IsPrintableASCII(str string) bool

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

func IsRGBcolor

func IsRGBcolor(str string) bool

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

func IsRequestURI

func IsRequestURI(rawurl string) bool

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

func IsRequestURL

func IsRequestURL(rawurl string) bool

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

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 check if string is valid semantic version

func IsURL

func IsURL(str string) bool

IsURL check if the string is an URL.

func IsUTFDigit

func IsUTFDigit(str string) bool

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

func IsUTFLetter

func IsUTFLetter(str string) bool

IsUTFLetter check 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 check if the string contains only unicode letters and numbers. Empty string is valid.

func IsUTFNumeric

func IsUTFNumeric(str string) bool

IsUTFNumeric check 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 check if the string is a UUID (version 3, 4 or 5).

func IsUUIDv3

func IsUUIDv3(str string) bool

IsUUIDv3 check if the string is a UUID version 3.

func IsUUIDv4

func IsUUIDv4(str string) bool

IsUUIDv4 check if the string is a UUID version 4.

func IsUUIDv5

func IsUUIDv5(str string) bool

IsUUIDv5 check if the string is a UUID version 5.

func IsUpperCase

func IsUpperCase(str string) bool

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

func IsVariableWidth

func IsVariableWidth(str string) bool

IsVariableWidth check 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

func LeftTrim

func LeftTrim(str, chars string) string

LeftTrim trim characters from the left-side of the input. If second argument is empty, it's will be 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 check if string matches the pattern (pattern is regular expression) In case of error return false

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 RemoveTags

func RemoveTags(s string) string

RemoveTags remove all tags from HTML string

func ReplacePattern

func ReplacePattern(str, pattern, replace string) string

ReplacePattern replace regular expression pattern in string

Example

This small example illustrate how to work with ReplacePattern function.

// 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 return reversed string

func RightTrim

func RightTrim(str, chars string) string

RightTrim trim characters from the right-side of the input. If second argument is empty, it's will be remove spaces.

func SafeFileName

func SafeFileName(str string) string

SafeFileName return 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 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

func StringLength

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

StringLength check 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 remove 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.

func ToFloat

func ToFloat(str string) (float64, error)

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

func ToInt

func ToInt(str string) (int64, error)

ToInt convert the input string to an integer, or 0 if the input is not an integer.

func ToJSON

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

ToJSON convert the input to a valid JSON string

func ToString

func ToString(obj interface{}) string

ToString convert the input to a string.

func Trim

func Trim(str, chars string) string

Trim trim characters from both sides of the input. If second argument is empty, it's will be remove spaces.

Example

This small example illustrate how to work with Trim function.

// 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

Will truncate a string closest length without breaking words.

func UnderscoreToCamelCase

func UnderscoreToCamelCase(s string) string

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

func ValidateStruct

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

ValidateStruct use tags for fields

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 WhiteList

func WhiteList(str, chars string) string

WhiteList remove characters that do not appear in the whitelist.

Example

This small example illustrate how to work with WhiteList function.

// 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{}) bool

CustomTypeValidator is a wrapper for validator functions that returns bool and accepts any type.

type Error

type Error struct {
	Name string
	Err  error
}

func (Error) Error

func (e Error) Error() string

type Errors

type Errors []error

func (Errors) Error

func (es Errors) Error() string

func (Errors) Errors

func (es Errors) Errors() []error

type ISO3166Entry

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

ISO3166Entry stores country codes

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 accepts additional parameters.

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