• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

.circleci/H24-Apr-2019-1110

.github/H24-Apr-2019-20

.travis.ymlH A D24-Apr-2019122 1512

CONTRIBUTING.mdH A D24-Apr-20194.1 KiB6345

LICENSEH A D24-Apr-20191.1 KiB2117

README.mdH A D24-Apr-201920.4 KiB507450

arrays.goH A D24-Apr-20191.9 KiB5942

arrays_test.goH A D24-Apr-20192.9 KiB117101

converter.goH A D24-Apr-20191.4 KiB6551

converter_test.goH A D24-Apr-20192.3 KiB7969

error.goH A D24-Apr-2019904 4430

error_test.goH A D24-Apr-2019911 3026

numerics.goH A D24-Apr-20192.7 KiB9870

numerics_test.goH A D24-Apr-201911.8 KiB550511

patterns.goH A D24-Apr-20197.8 KiB10292

types.goH A D24-Apr-201932.6 KiB637595

utils.goH A D24-Apr-20197.8 KiB271194

utils_benchmark_test.goH A D24-Apr-2019353 1814

utils_test.goH A D24-Apr-201912.9 KiB503441

validator.goH A D24-Apr-201934.2 KiB1,279977

validator_test.goH A D24-Apr-201988.6 KiB3,4913,157

wercker.ymlH A D24-Apr-2019235 1613

README.md

1govalidator
2===========
3[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/asaskevich/govalidator?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [![GoDoc](https://godoc.org/github.com/asaskevich/govalidator?status.png)](https://godoc.org/github.com/asaskevich/govalidator) [![Coverage Status](https://img.shields.io/coveralls/asaskevich/govalidator.svg)](https://coveralls.io/r/asaskevich/govalidator?branch=master) [![wercker status](https://app.wercker.com/status/1ec990b09ea86c910d5f08b0e02c6043/s "wercker status")](https://app.wercker.com/project/bykey/1ec990b09ea86c910d5f08b0e02c6043)
4[![Build Status](https://travis-ci.org/asaskevich/govalidator.svg?branch=master)](https://travis-ci.org/asaskevich/govalidator) [![Go Report Card](https://goreportcard.com/badge/github.com/asaskevich/govalidator)](https://goreportcard.com/report/github.com/asaskevich/govalidator) [![GoSearch](http://go-search.org/badge?id=github.com%2Fasaskevich%2Fgovalidator)](http://go-search.org/view?id=github.com%2Fasaskevich%2Fgovalidator) [![Backers on Open Collective](https://opencollective.com/govalidator/backers/badge.svg)](#backers) [![Sponsors on Open Collective](https://opencollective.com/govalidator/sponsors/badge.svg)](#sponsors) [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fasaskevich%2Fgovalidator.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fasaskevich%2Fgovalidator?ref=badge_shield)
5
6A package of validators and sanitizers for strings, structs and collections. Based on [validator.js](https://github.com/chriso/validator.js).
7
8#### Installation
9Make sure that Go is installed on your computer.
10Type the following command in your terminal:
11
12	go get github.com/asaskevich/govalidator
13
14or you can get specified release of the package with `gopkg.in`:
15
16	go get gopkg.in/asaskevich/govalidator.v4
17
18After it the package is ready to use.
19
20
21#### Import package in your project
22Add following line in your `*.go` file:
23```go
24import "github.com/asaskevich/govalidator"
25```
26If you are unhappy to use long `govalidator`, you can do something like this:
27```go
28import (
29  valid "github.com/asaskevich/govalidator"
30)
31```
32
33#### Activate behavior to require all fields have a validation tag by default
34`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.
35
36`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.
37
38```go
39import "github.com/asaskevich/govalidator"
40
41func init() {
42  govalidator.SetFieldsRequiredByDefault(true)
43}
44```
45
46Here's some code to explain it:
47```go
48// this struct definition will fail govalidator.ValidateStruct() (and the field values do not matter):
49type exampleStruct struct {
50  Name  string ``
51  Email string `valid:"email"`
52}
53
54// this, however, will only fail when Email is empty or an invalid email address:
55type exampleStruct2 struct {
56  Name  string `valid:"-"`
57  Email string `valid:"email"`
58}
59
60// lastly, this will only fail when Email is an invalid email address but not when it's empty:
61type exampleStruct2 struct {
62  Name  string `valid:"-"`
63  Email string `valid:"email,optional"`
64}
65```
66
67#### Recent breaking changes (see [#123](https://github.com/asaskevich/govalidator/pull/123))
68##### Custom validator function signature
69A context was added as the second parameter, for structs this is the object being validated – this makes dependent validation possible.
70```go
71import "github.com/asaskevich/govalidator"
72
73// old signature
74func(i interface{}) bool
75
76// new signature
77func(i interface{}, o interface{}) bool
78```
79
80##### Adding a custom validator
81This was changed to prevent data races when accessing custom validators.
82```go
83import "github.com/asaskevich/govalidator"
84
85// before
86govalidator.CustomTypeTagMap["customByteArrayValidator"] = CustomTypeValidator(func(i interface{}, o interface{}) bool {
87  // ...
88})
89
90// after
91govalidator.CustomTypeTagMap.Set("customByteArrayValidator", CustomTypeValidator(func(i interface{}, o interface{}) bool {
92  // ...
93}))
94```
95
96#### List of functions:
97```go
98func Abs(value float64) float64
99func BlackList(str, chars string) string
100func ByteLength(str string, params ...string) bool
101func CamelCaseToUnderscore(str string) string
102func Contains(str, substring string) bool
103func Count(array []interface{}, iterator ConditionIterator) int
104func Each(array []interface{}, iterator Iterator)
105func ErrorByField(e error, field string) string
106func ErrorsByField(e error) map[string]string
107func Filter(array []interface{}, iterator ConditionIterator) []interface{}
108func Find(array []interface{}, iterator ConditionIterator) interface{}
109func GetLine(s string, index int) (string, error)
110func GetLines(s string) []string
111func InRange(value, left, right float64) bool
112func IsASCII(str string) bool
113func IsAlpha(str string) bool
114func IsAlphanumeric(str string) bool
115func IsBase64(str string) bool
116func IsByteLength(str string, min, max int) bool
117func IsCIDR(str string) bool
118func IsCreditCard(str string) bool
119func IsDNSName(str string) bool
120func IsDataURI(str string) bool
121func IsDialString(str string) bool
122func IsDivisibleBy(str, num string) bool
123func IsEmail(str string) bool
124func IsFilePath(str string) (bool, int)
125func IsFloat(str string) bool
126func IsFullWidth(str string) bool
127func IsHalfWidth(str string) bool
128func IsHexadecimal(str string) bool
129func IsHexcolor(str string) bool
130func IsHost(str string) bool
131func IsIP(str string) bool
132func IsIPv4(str string) bool
133func IsIPv6(str string) bool
134func IsISBN(str string, version int) bool
135func IsISBN10(str string) bool
136func IsISBN13(str string) bool
137func IsISO3166Alpha2(str string) bool
138func IsISO3166Alpha3(str string) bool
139func IsISO693Alpha2(str string) bool
140func IsISO693Alpha3b(str string) bool
141func IsISO4217(str string) bool
142func IsIn(str string, params ...string) bool
143func IsInt(str string) bool
144func IsJSON(str string) bool
145func IsLatitude(str string) bool
146func IsLongitude(str string) bool
147func IsLowerCase(str string) bool
148func IsMAC(str string) bool
149func IsMongoID(str string) bool
150func IsMultibyte(str string) bool
151func IsNatural(value float64) bool
152func IsNegative(value float64) bool
153func IsNonNegative(value float64) bool
154func IsNonPositive(value float64) bool
155func IsNull(str string) bool
156func IsNumeric(str string) bool
157func IsPort(str string) bool
158func IsPositive(value float64) bool
159func IsPrintableASCII(str string) bool
160func IsRFC3339(str string) bool
161func IsRFC3339WithoutZone(str string) bool
162func IsRGBcolor(str string) bool
163func IsRequestURI(rawurl string) bool
164func IsRequestURL(rawurl string) bool
165func IsSSN(str string) bool
166func IsSemver(str string) bool
167func IsTime(str string, format string) bool
168func IsURL(str string) bool
169func IsUTFDigit(str string) bool
170func IsUTFLetter(str string) bool
171func IsUTFLetterNumeric(str string) bool
172func IsUTFNumeric(str string) bool
173func IsUUID(str string) bool
174func IsUUIDv3(str string) bool
175func IsUUIDv4(str string) bool
176func IsUUIDv5(str string) bool
177func IsUpperCase(str string) bool
178func IsVariableWidth(str string) bool
179func IsWhole(value float64) bool
180func LeftTrim(str, chars string) string
181func Map(array []interface{}, iterator ResultIterator) []interface{}
182func Matches(str, pattern string) bool
183func NormalizeEmail(str string) (string, error)
184func PadBoth(str string, padStr string, padLen int) string
185func PadLeft(str string, padStr string, padLen int) string
186func PadRight(str string, padStr string, padLen int) string
187func Range(str string, params ...string) bool
188func RemoveTags(s string) string
189func ReplacePattern(str, pattern, replace string) string
190func Reverse(s string) string
191func RightTrim(str, chars string) string
192func RuneLength(str string, params ...string) bool
193func SafeFileName(str string) string
194func SetFieldsRequiredByDefault(value bool)
195func Sign(value float64) float64
196func StringLength(str string, params ...string) bool
197func StringMatches(s string, params ...string) bool
198func StripLow(str string, keepNewLines bool) string
199func ToBoolean(str string) (bool, error)
200func ToFloat(str string) (float64, error)
201func ToInt(str string) (int64, error)
202func ToJSON(obj interface{}) (string, error)
203func ToString(obj interface{}) string
204func Trim(str, chars string) string
205func Truncate(str string, length int, ending string) string
206func UnderscoreToCamelCase(s string) string
207func ValidateStruct(s interface{}) (bool, error)
208func WhiteList(str, chars string) string
209type ConditionIterator
210type CustomTypeValidator
211type Error
212func (e Error) Error() string
213type Errors
214func (es Errors) Error() string
215func (es Errors) Errors() []error
216type ISO3166Entry
217type Iterator
218type ParamValidator
219type ResultIterator
220type UnsupportedTypeError
221func (e *UnsupportedTypeError) Error() string
222type Validator
223```
224
225#### Examples
226###### IsURL
227```go
228println(govalidator.IsURL(`http://user@pass:domain.com/path/page`))
229```
230###### ToString
231```go
232type User struct {
233	FirstName string
234	LastName string
235}
236
237str := govalidator.ToString(&User{"John", "Juan"})
238println(str)
239```
240###### Each, Map, Filter, Count for slices
241Each iterates over the slice/array and calls Iterator for every item
242```go
243data := []interface{}{1, 2, 3, 4, 5}
244var fn govalidator.Iterator = func(value interface{}, index int) {
245	println(value.(int))
246}
247govalidator.Each(data, fn)
248```
249```go
250data := []interface{}{1, 2, 3, 4, 5}
251var fn govalidator.ResultIterator = func(value interface{}, index int) interface{} {
252	return value.(int) * 3
253}
254_ = govalidator.Map(data, fn) // result = []interface{}{1, 6, 9, 12, 15}
255```
256```go
257data := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
258var fn govalidator.ConditionIterator = func(value interface{}, index int) bool {
259	return value.(int)%2 == 0
260}
261_ = govalidator.Filter(data, fn) // result = []interface{}{2, 4, 6, 8, 10}
262_ = govalidator.Count(data, fn) // result = 5
263```
264###### ValidateStruct [#2](https://github.com/asaskevich/govalidator/pull/2)
265If 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:
266```go
267govalidator.TagMap["duck"] = govalidator.Validator(func(str string) bool {
268	return str == "duck"
269})
270```
271For completely custom validators (interface-based), see below.
272
273Here is a list of available validators for struct fields (validator - used function):
274```go
275"email":              IsEmail,
276"url":                IsURL,
277"dialstring":         IsDialString,
278"requrl":             IsRequestURL,
279"requri":             IsRequestURI,
280"alpha":              IsAlpha,
281"utfletter":          IsUTFLetter,
282"alphanum":           IsAlphanumeric,
283"utfletternum":       IsUTFLetterNumeric,
284"numeric":            IsNumeric,
285"utfnumeric":         IsUTFNumeric,
286"utfdigit":           IsUTFDigit,
287"hexadecimal":        IsHexadecimal,
288"hexcolor":           IsHexcolor,
289"rgbcolor":           IsRGBcolor,
290"lowercase":          IsLowerCase,
291"uppercase":          IsUpperCase,
292"int":                IsInt,
293"float":              IsFloat,
294"null":               IsNull,
295"uuid":               IsUUID,
296"uuidv3":             IsUUIDv3,
297"uuidv4":             IsUUIDv4,
298"uuidv5":             IsUUIDv5,
299"creditcard":         IsCreditCard,
300"isbn10":             IsISBN10,
301"isbn13":             IsISBN13,
302"json":               IsJSON,
303"multibyte":          IsMultibyte,
304"ascii":              IsASCII,
305"printableascii":     IsPrintableASCII,
306"fullwidth":          IsFullWidth,
307"halfwidth":          IsHalfWidth,
308"variablewidth":      IsVariableWidth,
309"base64":             IsBase64,
310"datauri":            IsDataURI,
311"ip":                 IsIP,
312"port":               IsPort,
313"ipv4":               IsIPv4,
314"ipv6":               IsIPv6,
315"dns":                IsDNSName,
316"host":               IsHost,
317"mac":                IsMAC,
318"latitude":           IsLatitude,
319"longitude":          IsLongitude,
320"ssn":                IsSSN,
321"semver":             IsSemver,
322"rfc3339":            IsRFC3339,
323"rfc3339WithoutZone": IsRFC3339WithoutZone,
324"ISO3166Alpha2":      IsISO3166Alpha2,
325"ISO3166Alpha3":      IsISO3166Alpha3,
326```
327Validators with parameters
328
329```go
330"range(min|max)": Range,
331"length(min|max)": ByteLength,
332"runelength(min|max)": RuneLength,
333"stringlength(min|max)": StringLength,
334"matches(pattern)": StringMatches,
335"in(string1|string2|...|stringN)": IsIn,
336"rsapub(keylength)" : IsRsaPub,
337```
338
339And here is small example of usage:
340```go
341type Post struct {
342	Title    string `valid:"alphanum,required"`
343	Message  string `valid:"duck,ascii"`
344	Message2 string `valid:"animal(dog)"`
345	AuthorIP string `valid:"ipv4"`
346	Date     string `valid:"-"`
347}
348post := &Post{
349	Title:   "My Example Post",
350	Message: "duck",
351	Message2: "dog",
352	AuthorIP: "123.234.54.3",
353}
354
355// Add your own struct validation tags
356govalidator.TagMap["duck"] = govalidator.Validator(func(str string) bool {
357	return str == "duck"
358})
359
360// Add your own struct validation tags with parameter
361govalidator.ParamTagMap["animal"] = govalidator.ParamValidator(func(str string, params ...string) bool {
362    species := params[0]
363    return str == species
364})
365govalidator.ParamTagRegexMap["animal"] = regexp.MustCompile("^animal\\((\\w+)\\)$")
366
367result, err := govalidator.ValidateStruct(post)
368if err != nil {
369	println("error: " + err.Error())
370}
371println(result)
372```
373###### WhiteList
374```go
375// Remove all characters from string ignoring characters between "a" and "z"
376println(govalidator.WhiteList("a3a43a5a4a3a2a23a4a5a4a3a4", "a-z") == "aaaaaaaaaaaa")
377```
378
379###### Custom validation functions
380Custom validation using your own domain specific validators is also available - here's an example of how to use it:
381```go
382import "github.com/asaskevich/govalidator"
383
384type CustomByteArray [6]byte // custom types are supported and can be validated
385
386type StructWithCustomByteArray struct {
387  ID              CustomByteArray `valid:"customByteArrayValidator,customMinLengthValidator"` // multiple custom validators are possible as well and will be evaluated in sequence
388  Email           string          `valid:"email"`
389  CustomMinLength int             `valid:"-"`
390}
391
392govalidator.CustomTypeTagMap.Set("customByteArrayValidator", CustomTypeValidator(func(i interface{}, context interface{}) bool {
393  switch v := context.(type) { // you can type switch on the context interface being validated
394  case StructWithCustomByteArray:
395    // you can check and validate against some other field in the context,
396    // return early or not validate against the context at all – your choice
397  case SomeOtherType:
398    // ...
399  default:
400    // expecting some other type? Throw/panic here or continue
401  }
402
403  switch v := i.(type) { // type switch on the struct field being validated
404  case CustomByteArray:
405    for _, e := range v { // this validator checks that the byte array is not empty, i.e. not all zeroes
406      if e != 0 {
407        return true
408      }
409    }
410  }
411  return false
412}))
413govalidator.CustomTypeTagMap.Set("customMinLengthValidator", CustomTypeValidator(func(i interface{}, context interface{}) bool {
414  switch v := context.(type) { // this validates a field against the value in another field, i.e. dependent validation
415  case StructWithCustomByteArray:
416    return len(v.ID) >= v.CustomMinLength
417  }
418  return false
419}))
420```
421
422###### Custom error messages
423Custom error messages are supported via annotations by adding the `~` separator - here's an example of how to use it:
424```go
425type Ticket struct {
426  Id        int64     `json:"id"`
427  FirstName string    `json:"firstname" valid:"required~First name is blank"`
428}
429```
430
431#### Notes
432Documentation is available here: [godoc.org](https://godoc.org/github.com/asaskevich/govalidator).
433Full information about code coverage is also available here: [govalidator on gocover.io](http://gocover.io/github.com/asaskevich/govalidator).
434
435#### Support
436If you do have a contribution to the package, feel free to create a Pull Request or an Issue.
437
438#### What to contribute
439If you don't know what to do, there are some features and functions that need to be done
440
441- [ ] Refactor code
442- [ ] Edit docs and [README](https://github.com/asaskevich/govalidator/README.md): spellcheck, grammar and typo check
443- [ ] Create actual list of contributors and projects that currently using this package
444- [ ] Resolve [issues and bugs](https://github.com/asaskevich/govalidator/issues)
445- [ ] Update actual [list of functions](https://github.com/asaskevich/govalidator#list-of-functions)
446- [ ] Update [list of validators](https://github.com/asaskevich/govalidator#validatestruct-2) that available for `ValidateStruct` and add new
447- [ ] Implement new validators: `IsFQDN`, `IsIMEI`, `IsPostalCode`, `IsISIN`, `IsISRC` etc
448- [ ] Implement [validation by maps](https://github.com/asaskevich/govalidator/issues/224)
449- [ ] Implement fuzzing testing
450- [ ] Implement some struct/map/array utilities
451- [ ] Implement map/array validation
452- [ ] Implement benchmarking
453- [ ] Implement batch of examples
454- [ ] Look at forks for new features and fixes
455
456#### Advice
457Feel free to create what you want, but keep in mind when you implement new features:
458- Code must be clear and readable, names of variables/constants clearly describes what they are doing
459- Public functions must be documented and described in source file and added to README.md to the list of available functions
460- There are must be unit-tests for any new functions and improvements
461
462## Credits
463### Contributors
464
465This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)].
466
467#### Special thanks to [contributors](https://github.com/asaskevich/govalidator/graphs/contributors)
468* [Daniel Lohse](https://github.com/annismckenzie)
469* [Attila Oláh](https://github.com/attilaolah)
470* [Daniel Korner](https://github.com/Dadie)
471* [Steven Wilkin](https://github.com/stevenwilkin)
472* [Deiwin Sarjas](https://github.com/deiwin)
473* [Noah Shibley](https://github.com/slugmobile)
474* [Nathan Davies](https://github.com/nathj07)
475* [Matt Sanford](https://github.com/mzsanford)
476* [Simon ccl1115](https://github.com/ccl1115)
477
478<a href="graphs/contributors"><img src="https://opencollective.com/govalidator/contributors.svg?width=890" /></a>
479
480
481### Backers
482
483Thank you to all our backers! �� [[Become a backer](https://opencollective.com/govalidator#backer)]
484
485<a href="https://opencollective.com/govalidator#backers" target="_blank"><img src="https://opencollective.com/govalidator/backers.svg?width=890"></a>
486
487
488### Sponsors
489
490Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/govalidator#sponsor)]
491
492<a href="https://opencollective.com/govalidator/sponsor/0/website" target="_blank"><img src="https://opencollective.com/govalidator/sponsor/0/avatar.svg"></a>
493<a href="https://opencollective.com/govalidator/sponsor/1/website" target="_blank"><img src="https://opencollective.com/govalidator/sponsor/1/avatar.svg"></a>
494<a href="https://opencollective.com/govalidator/sponsor/2/website" target="_blank"><img src="https://opencollective.com/govalidator/sponsor/2/avatar.svg"></a>
495<a href="https://opencollective.com/govalidator/sponsor/3/website" target="_blank"><img src="https://opencollective.com/govalidator/sponsor/3/avatar.svg"></a>
496<a href="https://opencollective.com/govalidator/sponsor/4/website" target="_blank"><img src="https://opencollective.com/govalidator/sponsor/4/avatar.svg"></a>
497<a href="https://opencollective.com/govalidator/sponsor/5/website" target="_blank"><img src="https://opencollective.com/govalidator/sponsor/5/avatar.svg"></a>
498<a href="https://opencollective.com/govalidator/sponsor/6/website" target="_blank"><img src="https://opencollective.com/govalidator/sponsor/6/avatar.svg"></a>
499<a href="https://opencollective.com/govalidator/sponsor/7/website" target="_blank"><img src="https://opencollective.com/govalidator/sponsor/7/avatar.svg"></a>
500<a href="https://opencollective.com/govalidator/sponsor/8/website" target="_blank"><img src="https://opencollective.com/govalidator/sponsor/8/avatar.svg"></a>
501<a href="https://opencollective.com/govalidator/sponsor/9/website" target="_blank"><img src="https://opencollective.com/govalidator/sponsor/9/avatar.svg"></a>
502
503
504
505
506## License
507[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fasaskevich%2Fgovalidator.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fasaskevich%2Fgovalidator?ref=badge_large)