govalidator

package module
v0.0.0-...-2e06086 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2014 License: MIT Imports: 10 Imported by: 0

README

govalidator

GoDoc Coverage Status views wercker status

A package of string validators and sanitizers for Go lang. 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 BlackList(str, chars string) string
func CamelCaseToUnderscore(str string) string
func Contains(str, substring string) bool
func Escape(str string) string
func GetLine(s string, index int) (string, error)
func GetLines(s string) []string
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 IsDivisibleBy(str, num string) bool
func IsEmail(str string) bool
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, version int) 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 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 IsMultibyte(str string) bool
func IsNull(str string) bool
func IsNumeric(str string) bool
func IsRGBcolor(str string) bool
func IsURL(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 LeftTrim(str, chars string) string
func Matches(str, pattern 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 SafeFileName(str string) string
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 ToString(obj interface{}) (string, error)
func Trim(str, chars string) string
func UnderscoreToCamelCase(s string) string
func ValidateStruct(s interface{}) (bool, error)
func WhiteList(str, chars string) string
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)
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 ignore tag, place - in your tag. If you think, that package has no necessary validators, you can add it:

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):

"email":         IsEmail,
"url":           IsURL,
"alpha":         IsAlpha,
"alphanum":      IsAlphanumeric,
"numeric":       IsNumeric,
"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,
"fullwidth":     IsFullWidth,
"halfwidth":     IsHalfWidth,
"variablewidth": IsVariableWidth,
"base64":        IsBase64,
"datauri":       IsDataURI,
"ipv4":          IsIPv4,
"ipv6":          IsIPv6,
"mac":           IsMAC,
"latitude":      IsLatitude,
"longitude":     IsLongitude

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{"My Example Post", "duck", "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.

Bitdeli Badge

Documentation

Overview

Package govalidator is package of string validators and sanitizers. ver. 0.0.1

Index

Examples

Constants

View Source
const (
	Email        string = "" /* 1182-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})$"
	IPv4         string = "^(\\d?\\d?\\d)\\.(\\d?\\d?\\d)\\.(\\d?\\d?\\d)\\.(\\d?\\d?\\d)$"
	IPv6         string = "^::|^::1|^([a-fA-F0-9]{1,4}::?){1,7}([a-fA-F0-9]{1,4})$"
	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})$"
	DataURI      string = "^data:.+\\/(.+);base64$"
	MAC          string = "^([a-fA-F0-9]{2}[:-]){5}[a-fA-F0-9]{2}$"
	Latitude     string = "^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?)$"
	Longitude    string = "^[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$"
	URL          string = `` /* 301-byte string literal not displayed */

)

Basic regular expressions for validating strings

Variables

View Source
var TagMap = map[string]Validator{
	"email":         IsEmail,
	"url":           IsURL,
	"alpha":         IsAlpha,
	"alphanum":      IsAlphanumeric,
	"numeric":       IsNumeric,
	"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,
	"fullwidth":     IsFullWidth,
	"halfwidth":     IsHalfWidth,
	"variablewidth": IsVariableWidth,
	"base64":        IsBase64,
	"datauri":       IsDataURI,
	"ipv4":          IsIPv4,
	"ipv6":          IsIPv6,
	"mac":           IsMAC,
	"latitude":      IsLatitude,
	"longitude":     IsLongitude,
}

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

Functions

func BlackList

func BlackList(str, chars string) string

BlackList remove characters that appear in the blacklist.

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 Escape

func Escape(str string) string

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

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 IsASCII

func IsASCII(str string) bool

IsASCII check if the string contains ASCII chars only.

func IsAlpha

func IsAlpha(str string) bool

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

func IsAlphanumeric

func IsAlphanumeric(str string) bool

IsAlphanumeric check if the string contains only letters and numbers.

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 IsDataURI

func IsDataURI(str string) bool

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

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

func IsHalfWidth

func IsHalfWidth(str string) bool

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

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, version int) bool

IsIP check if the string is an IP (version 4 or 6). If version value is not equal to 6 or 4, it will be check both variants.

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 IsInt

func IsInt(str string) bool

IsInt check if the string is an integer.

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.

func IsMAC

func IsMAC(str string) bool

IsMAC check if a string is valid MAC address. Possible MAC formats: 3D:F2:C9:A6:B3:4F 3D-F2-C9-A6-B3:4F 3d-f2-c9-a6-b3:4f

func IsMultibyte

func IsMultibyte(str string) bool

IsMultibyte check if the string contains one or more multibyte chars.

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.

func IsRGBcolor

func IsRGBcolor(str string) bool

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

func IsURL

func IsURL(str string) bool

IsURL check if the string is an URL.

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.

func IsVariableWidth

func IsVariableWidth(str string) bool

IsVariableWidth check if the string contains a mixture of full and half-width chars.

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

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

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 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 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 validator functions, that returns bool and accepts string.

Jump to

Keyboard shortcuts

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