# README
Fast and intuitive validation library for Go
This lib uses the Is...
validation functions from the govalidator project.
Installation
go get github.com/tiendc/go-validator
Usage
General usage
import (
vld "github.com/tiendc/go-validator"
)
type Person struct {
FirstName string
LastName string
Birthdate time.Time
Unemployed bool
Salary uint
Rank string
WorkEmail string
Projects []string
TaskMap map[string]Task
}
var p Person
errs := vld.Validate(
// Validate first and last names separately
vld.StrLen(&p.FirstName, 3, 30).OnError(
vld.SetField("first_name", nil),
vld.SetCustomKey("ERR_VLD_PERSON_FIRST_NAME_INVALID"),
),
vld.StrLen(&p.FirstName, 3, 30).OnError(
vld.SetField("last_name", nil),
vld.SetCustomKey("ERR_VLD_PERSON_LAST_NAME_INVALID"),
),
// OR use this to produce only one error when one of them fails
vld.Group(
vld.StrLen(&p.FirstName, 3, 30),
vld.StrLen(&p.LastName, 3, 30),
).OnError(
vld.SetField("name", nil),
vld.SetCustomKey("ERR_VLD_PERSON_NAME_INVALID"),
),
// Birthdate is optional, but when it's present, it must be within 1950 and now
vld.When(!p.Birthdate.IsZero()).Then(
vld.TimeRange(p.Birthdate, <1950-01-01>, time.Now()).OnError(...),
)
vld.When(!p.Unemployed).Then(
vld.Required(&p.Salary),
// Work email must be valid
vld.StrIsEmail(&p.WorkEmail),
// Rank must be one of the constants
vld.StrIn(&p.Rank, "Employee", "Manager", "Director"),
vld.Case(
vld.When(p.Rank == "Manager").Then(vld.NumGT(&p.Salary, 10000)),
vld.When(p.Rank == "Director").Then(vld.NumGT(&p.Salary, 30000)),
).Default(
vld.NumLT(&p.Salary, 10000),
),
// Projects are optional, but when they are present, they must be unique and sorted
vld.When(len(p.Projects) > 0).Then(
vld.SliceUnique(p.Projects).OnError(...),
vld.SliceSorted(p.Projects).OnError(...),
)
).Else(
// When person is unemployed
vld.NumEQ(&p.Salary, 0),
vld.StrEQ(&p.WorkEmail, ""),
),
// Validate slice elements
vld.Slice(p.Projects).ForEach(func(elem int, index int, validator ItemValidator) {
validator.Validate(
vld.StrLen(&elem, 10, 30).OnError(
vld.SetField(fmt.Sprintf("projects[%d]", index), nil),
vld.SetCustomKey("ERR_VLD_PROJECT_NAME_INVALID"),
),
)
}),
// Validate map entries
vld.Map(p.TaskMap).ForEach(func(k string, v Task, validator ItemValidator) {
validator.Validate(
vld.StrLen(&v.Name, 10, 30).OnError(
vld.SetField(fmt.Sprintf("taskMap[%s].name", k), nil),
vld.SetCustomKey("ERR_VLD_TASK_NAME_INVALID"),
),
)
}),
// OTHER FUNCTIONS
// Pass if at least one of the validations passes
vld.OneOf(
// List of validations
),
// Pass if exact one of the validations passes
vld.ExactOneOf(
// List of validations
),
// Pass if none of the validations passes
vld.NotOf(
// List of validations
),
)
for _, e := range errs {
detail, warnErr := e.BuildDetail()
fmt.Printf("%+v\n", detail)
}
Error message localization
- Method 1: inline localization (not recommended)
errs := Validate(
NumLTE(&p.Age, 40).OnError(
// Override the default template in english
SetTemplate("Tuổi nhân viên phải nhỏ hơn hoặc bằng {{.Max}}"),
),
)
for _, e := range errs {
detail, warnErr := e.BuildDetail()
fmt.Printf("%+v\n", detail)
}
- Method 2: using another localization lib (recommended)
// Supposed you have 2 files defining error messages
// In `error_messages.en`:
// ERR_VLD_EMPLOYEE_AGE_TOO_BIG = "Employee {{.EmployeeName}} has age bigger than {{.Max}}"
// In `error_messages.vi`:
// ERR_VLD_EMPLOYEE_AGE_TOO_BIG = "Nhân viên {{.EmployeeName}} có tuổi lớn hơn {{.Max}}"
errs := Validate(
NumLTE(&p.Age, 40).OnError(
// Custom param (the default template doesn't have this one)
SetParam("EmployeeName", p.Name),
// Custom key to define custom template to use
SetCustomKey("ERR_VLD_EMPLOYEE_AGE_TOO_BIG"),
),
)
for _, e := range errs {
errKey := e.CustomKey()
errParams : = e.Params() // or e.ParamsWithFormatter()
errorMsg := translationFunction(errKey, errParams) // You need to provide this function
fmt.Printf("%+v\n", errorMsg)
}
Custom error param formatter
errs := Validate(
NumLT(&budget, 1000000).OnError(
SetField("Budget", nil),
),
)
// e.BuildDetail() may produce message `Budget must be less than 1000000`,
// but you may want a message like: `Budget must be less than 1,000,000`.
// Let's use a custom formatter
errs := Validate(
NumLT(&budget, 1000000).OnError(
SetField("Budget", nil),
SetNumParamFormatter(NewDecimalFormatFunc('.', ',', "%f")),
),
)
Contributing
- You are welcome to make pull requests for new functions and bug fixes.
License
# Packages
No description provided by the author
# Functions
Case works like a `switch...case` statement.
DefaultLang default language used in the template.
ExactOneOf checks if the target value satisfies only one of the given validators.
GetTemplateProvider gets current template provider.
Group groups the given validators into one.
If a bare check validation convenient for validating custom data such as `If(myTime.Before(dueDate)).OnError(vld.SetCustomKey("MY_ERR_KEY"))`.
Map allows validating every map entry.
MapKeyIn validates the input map must have keys in the specified values.
MapKeyNotIn validates the input map must have keys not in the specified values.
MapKeyRange validates the input map must have keys in the specified range.
MapLen validates the input map must have length in the specified range.
MapValueIn validates the input map must have values in the specified values.
MapValueNotIn validates the input map must have values not in the specified values.
MapValueRange validates the input map must have values in the specified range.
MapValueUnique validates the input map must have unique values.
Must a bare check validation convenient for validating custom data such as `Must(myTime.Before(dueDate)).OnError(vld.SetCustomKey("MY_ERR_KEY"))`.
NewDecimalFormatFunc returns a FormatFunc which can format and group digits of decimal or integer.
NewDecimalNumFormatFunc returns a FormatFunc which groups digits of decimal.
NewError creates a new Error object.
NewField creates a new Field object.
NewJSONFormatFunc create a format func to format input as JSON output.
NewMapContentValidator creates a new MapContentValidator.
NewMapFormatFunc create a new func for formatting a map.
NewMultiCondValidator creates a new MultiCondValidator.
NewSingleCondValidator creates a new SingleCondValidator.
NewSingleValidator creates a new SingleValidator.
NewSliceContentValidator creates a new SliceContentValidator.
NewSliceFormatFunc create a new func for formatting a slice.
NewTypedParamFormatter creates a new TypedParamFormatter with using default format functions.
Nil validates the input pointer to be `nil`.
NotNil validates the input pointer to be not `nil`.
NotOf checks the target value not satisfy any of the given validators.
NumDivisibleBy validates the input number must be divisible by the specified value.
NumEQ validates the input number must equal to a value.
NumGT validates the input number must be greater than a value.
NumGTE validates the input number must be greater than or equal to a value.
NumIn validates the input number must be in the specified values.
NumJsSafeInt validates the input number must be a Javascript safe integer (max 2^53-1).
NumLT validates the input number must be less than a value.
NumLTE validates the input number must be less than or equal to a value.
NumNotIn validates the input number must be not in the specified values.
NumRange validates the input number must be in the specified range.
OneOf checks if the target value satisfies one of the given validators.
Required validates the input to be required.
SetBoolParamFormatter returns a ErrorMod function to set format function for bools.
SetCustomKey returns a ErrorMod function to set custom key of error.
SetCustomParamFormatter returns a ErrorMod function to set custom format function.
SetDefaultLang set default language used in the template.
SetField returns a ErrorMod function to set field of error.
SetMapParamFormatter returns a ErrorMod function to set format function for maps.
SetNumParamFormatter returns a ErrorMod function to set format function for numbers.
SetParam returns a ErrorMod function to set a param of error.
SetParamFormatter returns a ErrorMod function to set params formatter of error.
SetPtrParamFormatter returns a ErrorMod function to set format function for pointers.
SetSliceParamFormatter returns a ErrorMod function to set format function for slices.
SetStrParamFormatter returns a ErrorMod function to set format function for strings.
SetStructParamFormatter returns a ErrorMod function to set format function for structs.
SetTemplate returns a ErrorMod function to set template of error.
SetTemplateProvider sets current template provider.
Slice allows validating slice elements.
SliceElemIn validates the input slice must contain items in the specified values.
SliceElemNotIn validates the input slice must contain items not in the specified values.
SliceElemRange validates the input slice must contain items in the specified range.
SliceLen validates the input slice must have length in the specified range.
SliceSorted validates the input slice must be sorted in ascending order.
SliceSortedDesc validates the input slice must be sorted in descending order.
SliceUnique validates the input slice must contain only unique items.
StrByteLen validates the input string must have length of bytes in the specified range.
StrByteMatch validates the input string must have bytes matching the specified regex.
StrEQ validates the input string must equal to the specified value.
StrHasLowerCase validates the input string must contain at least 1 lower case character.
StrHasUpperCase validates the input string must contain at least 1 upper case character.
StrHasWhitespace validates the input string must contain at least 1 whitespace character.
StrHasWhitespaceOnly validates the input string must contain whitespaces only.
StrIn validates the input string must be in the specified values.
StrIsAlpha validates the input string must contain only characters in range a-zA-Z.
StrIsAlphanumeric validates the input string must contain only characters in range a-zA-Z0-9.
StrIsASCII validates the input string must contain only ASCII characters.
StrIsBase64 validates the input string must be in Base64 format.
StrIsCIDR validates the input string must be in CIDR format.
StrIsCRC32 validates the input string must be in CRC32 format.
StrIsCRC32b validates the input string must be in CRC32b format.
StrIsCreditCard validates the input string must be a credit card number.
StrIsDataURI validates the input string must be a data URI.
StrIsDialString validates the input string must be a dial string such as a hostname, IP, or a port.
StrIsDNSName validates the input string must be a domain name.
StrIsE164 validates the input string must be in E164 format.
StrIsEmail validates the input string must be a valid email.
StrIsExistingEmail validates the input string must be a valid email of existing domain.
StrIsFilePath validates the input string must be a file path in both Windows or Unix.
StrIsFloat validates the input string must be a floating number.
StrIsFullWidth validates the input string must contain only full-width characters.
StrIsHalfWidth validates the input string must contain only half-width characters.
StrIsHexadecimal validates the input string must be in hex format.
StrIsHexcolor validates the input string must be a hex color such as #fab or #aabbcc.
StrIsHost validates the input string must be a hostname or an IP.
StrIsIMEI validates the input string must be an IMEI.
StrIsIMSI validates the input string must be an IMSI.
StrIsInt validates the input string must be an integral number.
StrIsIP validates the input string must be in IP v4 or IP v6 format.
StrIsIPv4 validates the input string must be in IP v4 format.
StrIsIPv6 validates the input string must be in IP v6 format.
StrIsISBN validates the input string must be a ISBN v10 or ISBN v13.
StrIsISBN10 validates the input string must be a ISBN v10.
StrIsISBN13 validates the input string must be a ISBN v13.
StrIsISO3166Alpha2 validates the input string must be one of ISO3166 Alpha2 country codes.
StrIsISO3166Alpha3 validates the input string must be one of ISO3166 Alpha3 country codes.
StrIsISO4217 validates the input string must be one of ISO4217 currency codes.
StrIsISO639Alpha2 validates the input string must be one of ISO639 Alpha2 language codes.
StrIsISO639Alpha3b validates the input string must be one of ISO639 Alpha3b language codes.
StrIsJSON validates the input string must be in JSON format.
StrIsLatitude validates the input string must be a latitude number.
StrIsLongitude validates the input string must be a longitude number.
StrIsLowerCase validates the input string must be in lower case.
StrIsMAC validates the input string must be in MAC address format.
StrIsMagnetURI validates the input string must be a magnet URI.
StrIsMD4 validates the input string must be in MD4 format.
StrIsMD5 validates the input string must be in MD5 format.
StrIsMongoID validates the input string must be a Mongo ID.
StrIsMultibyte validates the input string must be a multiple-byte string.
StrIsNumeric validates the input string must contain only characters in range 0-9.
StrIsPort validates the input string must be a valid port number (range 1-65535).
StrIsPrintableASCII validates the input string must contain only printable ASCII characters.
StrIsRegex validates the input string must be a regex.
StrIsRequestURI validates the input string must be a valid request URI.
StrIsRequestURL validates the input string must be a valid request URL (URL confirm to RFC 3986).
StrIsRFC3339 validates the input string must be a date time of RFC3339 layout.
StrIsRFC3339WithoutZone validates the input string must be a date time of RFC3339 layout without time zone.
StrIsRGBcolor validates the input string must be a rgb color such as rgb(10,20,30).
StrIsRipeMD128 validates the input string must be in RipeMD128 format.
StrIsRipeMD160 validates the input string must be in RipeMD160 format.
StrIsRsaPublicKey validates the input string must be an RSA public key.
StrIsSemver validates the input string must be a Semver.
StrIsSHA1 validates the input string must be in SHA1 format.
StrIsSHA256 validates the input string must be in SHA256 format.
StrIsSHA3224 validates the input string must be in SHA3-224 format.
StrIsSHA3256 validates the input string must be in SHA3-256 format.
StrIsSHA3384 validates the input string must be in SHA3-384 format.
StrIsSHA3512 validates the input string must be in SHA3-512 format.
StrIsSHA384 validates the input string must be in SHA384 format.
StrIsSHA512 validates the input string must be in SHA512 format.
StrIsSSN validates the input string must be a SSN.
StrIsTiger128 validates the input string must be in Tiger128 format.
StrIsTiger160 validates the input string must be in Tiger160 format.
StrIsTiger192 validates the input string must be in Tiger192 format.
StrIsTime validates the input string must be a date time of the specified layout.
StrIsULID validates the input string must be a ULID.
StrIsUnixFilePath validates the input string must be a file path in Unix.
StrIsUnixTime validates the input string must be a unix time value.
StrIsUpperCase validates the input string must be in upper case.
StrIsURL validates the input string must be a valid URL.
StrIsUTFDigit validates the input string must contain only UTF digits.
StrIsUTFLetter validates the input string must contain only UTF letters.
StrIsUTFLetterNumeric validates the input string must contain only UTF letters and numerics.
StrIsUTFNumeric validates the input string must contain only UTF numeric characters.
StrIsUUID validates the input string must be a UUID v3 or UUID v4 or UUID v5.
StrIsUUIDv3 validates the input string must be a UUID v3.
StrIsUUIDv4 validates the input string must be a UUID v4.
StrIsUUIDv5 validates the input string must be a UUID v5.
StrIsVariableWidth validates the input string must contain variable-width characters.
StrIsWinFilePath validates the input string must be a file path in Windows.
StrLen validates the input string must have length of runes in the specified range.
StrMatch validates the input string must have runes matching the specified regex.
StrNotIn validates the input string must be not in the specified values.
TimeEQ validates the input time must equal to the specified value.
TimeGT validates the input time must be greater than the specified value.
TimeGTE validates the input time must be greater than or equal to the specified value.
TimeIn validates the input time must be in the specified values.
TimeLT validates the input time must be less than the specified value.
TimeLTE validates the input time must be less than or equal to the specified value.
TimeNotIn validates the input time must be not in the specified values.
TimeRange validates the input time must be in the specified range.
TimeValid validates the input time must be not zero value.
ToFloat64 transforms a number to float64 value.
ToInt64 transforms a number to int64 value.
ToLower transforms characters of a string to lowercase
Example: validation.StrIsEmail(validation.ToLower(&req.Email)).
ToUint64 transforms a number to uint64 value.
ToUpper transforms characters of a string to uppercase.
Validate executes given validators to make result.
ValidateWithCtx executes given validators with given context.
When works like a `if...then...else` statement.
# Variables
Errors can be returned from the lib.
Errors can be returned from the lib.
# Interfaces
CondValidator interface represents a validator that performs multiple validations based on specified conditions.
No description provided by the author
No description provided by the author
ItemValidator validator to collect input validators via its Validate() func.
MapContentValidator validator that validates map entries.
MultiCondValidator validator that accepts multiple conditions.
SingleCondValidator validator that accepts only one condition.
SingleValidator interface represents a validator that performs a single validation.
SliceContentValidator validator that validates slice elements.
TemplateProvider interface for providing template for generating error messages.
No description provided by the author
Validator interface represents a validator object.
# Type aliases
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author