MSP-8974 up deps
This commit is contained in:
1 parent
0abaaf740f
commit
a0aafd93b9
602 files changed
+47724
-13295
No files matched your search
@@ -7,6 +7,8 @@
|
||||
_obj
|
||||
_test
|
||||
bin
|
||||
.gocache/
|
||||
.gomodcache/
|
||||
|
||||
# Architecture specific extensions/prefixes
|
||||
*.[568vq]
|
||||
@@ -30,3 +32,4 @@ _testmain.go
|
||||
cover.html
|
||||
README.html
|
||||
.idea
|
||||
.claude/
|
||||
+9
@@ -2,6 +2,8 @@ version: "2"
|
||||
linters:
|
||||
default: all
|
||||
disable:
|
||||
- noinlineerr
|
||||
- wsl_v5
|
||||
- copyloopvar
|
||||
- cyclop
|
||||
- depguard
|
||||
@@ -12,6 +14,7 @@ linters:
|
||||
- errorlint
|
||||
- exhaustive
|
||||
- exhaustruct
|
||||
- exhaustruct_v5
|
||||
- forbidigo
|
||||
- forcetypeassert
|
||||
- funlen
|
||||
@@ -30,6 +33,7 @@ linters:
|
||||
- maintidx
|
||||
- misspell
|
||||
- mnd
|
||||
- modernize
|
||||
- nakedret
|
||||
- nestif
|
||||
- nilnil
|
||||
@@ -50,3 +54,8 @@ linters:
|
||||
- varnamelen
|
||||
- wrapcheck
|
||||
- wsl
|
||||
- gomodguard
|
||||
settings:
|
||||
govet:
|
||||
disable:
|
||||
- inline
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## Repository
|
||||
|
||||
`github.com/go-playground/validator/v10` — struct and field validation library based on struct tags. The module path ends in `/v10`; changes must preserve v10 API compatibility. Contributions require test coverage (see `.github/CONTRIBUTING.md`).
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
make test # go test -cover -race ./...
|
||||
make lint # installs golangci-lint v2.0.2 if missing, then runs it
|
||||
make bench # go test -run=NONE -bench=. -benchmem ./...
|
||||
|
||||
# Single test / subtest
|
||||
go test -run TestName ./...
|
||||
go test -run TestName/subtest_name ./...
|
||||
|
||||
# Single benchmark
|
||||
go test -run=NONE -bench=BenchmarkFieldSuccess -benchmem ./...
|
||||
```
|
||||
|
||||
Tests live alongside source in the package root (`validator_test.go`, `benchmarks_test.go`); run them from the repo root. Non-standard validators and translations are separate packages (`./non-standard/validators`, `./translations/...`) and are included by `./...`.
|
||||
|
||||
## Architecture
|
||||
|
||||
The library compiles validation tags into cached execution plans, then runs them against values via reflection. Understanding three layers is enough to be productive:
|
||||
|
||||
### 1. Registration & configuration — [validator_instance.go](validator_instance.go)
|
||||
`Validate` is the singleton entry point. It holds:
|
||||
- `validations` — tag → `FuncCtx` (the validator functions)
|
||||
- `aliases` — shorthand tag → expanded tag expression
|
||||
- `customFuncs` — `reflect.Type` → value extractor (for types like `sql.NullString` or anything implementing the `Valuer` interface, see [doc.go](doc.go))
|
||||
- `structLevelFuncs` — struct-level validators
|
||||
- `tagCache` and `structCache` — parsed-tag and parsed-struct caches (critical for performance; `Validate` is thread-safe and must be used as a singleton)
|
||||
|
||||
Options live in [options.go](options.go) (`WithRequiredStructEnabled`, `WithPrivateFieldValidation`, etc.). `WithRequiredStructEnabled` is the forward-compatible default users should adopt before v11.
|
||||
|
||||
### 2. Baked-in validators — [baked_in.go](baked_in.go)
|
||||
All built-in tags (`required`, `email`, `uuid`, `oneof`, `gt`, cross-field `eqfield`, etc.) are registered here as `Func`/`FuncCtx` receiving a `FieldLevel` (see [field_level.go](field_level.go)). `restrictedTags` enumerates names that cannot be overridden. Cross-field validators resolve the other field via `fl.GetStructFieldOK*` against the parent struct captured in the execution context.
|
||||
|
||||
Adjacent data tables:
|
||||
- [regexes.go](regexes.go), [postcode_regexes.go](postcode_regexes.go) — compiled regexps used by validators
|
||||
- [country_codes.go](country_codes.go), [currency_codes.go](currency_codes.go), [language_codes.go](language_codes.go) — lookup tables
|
||||
|
||||
When adding a new tag: register it in `bakedInValidators` in [baked_in.go](baked_in.go), add its description to the table in [README.md](README.md), and add tests in [validator_test.go](validator_test.go).
|
||||
|
||||
### 3. Execution — [validator.go](validator.go) + [cache.go](cache.go)
|
||||
- [cache.go](cache.go) parses struct tags into `cField` and `cTag` linked lists once per type and stores them in `structCache`/`tagCache`. `cTag.typeof` (`typeDefault`, `typeOmitEmpty`, `typeDive`, `typeStructOnly`, `typeOr`, etc.) tells the executor what to do.
|
||||
- [validator.go](validator.go) contains the per-call `validate` struct (pooled via `sync.Pool`) and the `validateStruct` / `traverseField` mutual recursion. `ns`/`actualNs` are the accumulated dotted namespaces used in error paths; `dive`, `keys`, `endkeys` push/pop through slices/maps.
|
||||
|
||||
Public entry points live on `Validate`: `Struct`, `StructCtx`, `StructPartial`, `StructExcept`, `StructFiltered`, `Var`, `VarWithValue`, and their `Ctx` variants.
|
||||
|
||||
### Errors
|
||||
[errors.go](errors.go) defines `ValidationErrors` (a `[]FieldError`) and `InvalidValidationError`. Per [README.md](README.md) and [doc.go](doc.go), callers type-assert `err.(validator.ValidationErrors)` after checking `err != nil`. Only `InvalidValidationError` signals misuse (e.g. passing a non-struct to `Struct`).
|
||||
|
||||
### Struct-level & field-level custom validators
|
||||
[struct_level.go](struct_level.go) and [field_level.go](field_level.go) define the contexts passed to user-registered functions. Struct-level validators report errors via `StructLevel.ReportError` / `ReportValidationErrors` — they operate on the whole struct instead of a single field.
|
||||
|
||||
### Translations — [translations.go](translations.go) + [translations/](translations/)
|
||||
Each locale under `translations/<locale>` registers a human-readable message per tag against a `ut.Translator`. `FieldError.Translate(trans)` consumes the registered `TranslationFunc`. When adding a new tag with a translation, add an entry in each locale package — translations are parallel packages, not a single table.
|
||||
|
||||
### Non-standard validators — [non-standard/validators/](non-standard/validators/)
|
||||
Opt-in validators (`NotBlank`) users register manually. Keep niche or opinionated validators here rather than expanding `baked_in.go`.
|
||||
|
||||
## Performance-sensitive areas
|
||||
|
||||
Validation is on the hot path for many users. When touching [cache.go](cache.go), [validator.go](validator.go), or `baked_in.go` hot functions:
|
||||
- Avoid allocations in the success path — several baked-in validators and the executor reuse pooled buffers (`validate.misc`, `str1`, `str2`).
|
||||
- Benchmarks in [benchmarks_test.go](benchmarks_test.go) gate regressions; run `make bench` before and after significant changes and include results in the PR if they move.
|
||||
|
||||
## Conventions
|
||||
|
||||
- Go module minimum version is pinned in [go.mod](go.mod); don't lower it.
|
||||
- Don't introduce new top-level exported types without need — most extension happens through `Register*` methods on `Validate`.
|
||||
- `restrictedTags` (in [baked_in.go](baked_in.go)) is intentionally a denylist for aliases and registrations; adding a tag with one of those names will break the parser.
|
||||
- Examples live under `_examples/` (underscore prefix excludes them from the module build). Keep them runnable as standalone `main` packages.
|
||||
+1
-1
@@ -3,7 +3,7 @@ GOCMD=go
|
||||
linters-install:
|
||||
@golangci-lint --version >/dev/null 2>&1 || { \
|
||||
echo "installing linting tools..."; \
|
||||
curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh| sh -s v2.0.2; \
|
||||
curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh| sh -s v2.13.1; \
|
||||
}
|
||||
|
||||
lint: linters-install
|
||||
|
||||
+25
-10
@@ -15,7 +15,7 @@ It has the following **unique** features:
|
||||
- Slice, Array and Map diving, which allows any or all levels of a multidimensional field to be validated.
|
||||
- Ability to dive into both map keys and values for validation
|
||||
- Handles type interface by determining it's underlying type prior to validation.
|
||||
- Handles custom field types such as sql driver Valuer see [Valuer](https://golang.org/src/database/sql/driver/types.go?s=1210:1293#L29)
|
||||
- Handles custom field types such as sql driver [Valuer](https://golang.org/src/database/sql/driver/types.go?s=1210:1293#L29) and the [Valuer interface](https://github.com/go-playground/validator/blob/master/_examples/valuer/main.go)
|
||||
- Alias validation tags, which allows for mapping of several validations to a single tag for easier defining of validations on structs
|
||||
- Extraction of custom defined Field Name e.g. can specify to extract the JSON name while validating and have it available in the resulting FieldError
|
||||
- Customizable i18n aware error messages.
|
||||
@@ -24,7 +24,7 @@ It has the following **unique** features:
|
||||
A Call for Maintainers
|
||||
----------------------
|
||||
|
||||
Please read the discussiong started [here](https://github.com/go-playground/validator/discussions/1330) if you are interested in contributing/helping maintain this package.
|
||||
Please read the discussion started [here](https://github.com/go-playground/validator/discussions/1330) if you are interested in contributing/helping maintain this package.
|
||||
|
||||
Installation
|
||||
------------
|
||||
@@ -51,7 +51,8 @@ Validator returns only InvalidValidationError for bad validation input, nil or V
|
||||
|
||||
```go
|
||||
err := validate.Struct(mystruct)
|
||||
validationErrors := err.(validator.ValidationErrors)
|
||||
var validationErrors validator.ValidationErrors
|
||||
errors.As(err, &validationErrors)
|
||||
```
|
||||
|
||||
Usage and documentation
|
||||
@@ -84,7 +85,7 @@ validate := validator.New(validator.WithRequiredStructEnabled())
|
||||
| eqcsfield | Field Equals Another Field (relative)|
|
||||
| eqfield | Field Equals Another Field |
|
||||
| fieldcontains | Check the indicated characters are present in the Field |
|
||||
| fieldexcludes | Check the indicated characters are not present in the field |
|
||||
| fieldexcludes | Current field does not contain another field's value |
|
||||
| gtcsfield | Field Greater Than Another Relative Field |
|
||||
| gtecsfield | Field Greater Than or Equal To Another Relative Field |
|
||||
| gtefield | Field Greater Than or Equal To Another Field |
|
||||
@@ -106,8 +107,9 @@ validate := validator.New(validator.WithRequiredStructEnabled())
|
||||
| datauri | Data URL |
|
||||
| fqdn | Full Qualified Domain Name (FQDN) |
|
||||
| hostname | Hostname RFC 952 |
|
||||
| hostname_port | HostPort |
|
||||
| hostname_rfc1123 | Hostname RFC 1123 |
|
||||
| hostname_port | HostPort |
|
||||
| port | Port number |
|
||||
| ip | Internet Protocol Address IP |
|
||||
| ip4_addr | Internet Protocol Address IPv4 |
|
||||
| ip6_addr | Internet Protocol Address IPv6 |
|
||||
@@ -122,18 +124,24 @@ validate := validator.New(validator.WithRequiredStructEnabled())
|
||||
| udp6_addr | User Datagram Protocol Address UDPv6 |
|
||||
| udp_addr | User Datagram Protocol Address UDP |
|
||||
| unix_addr | Unix domain socket end point Address |
|
||||
| uds_exists | Unix domain socket exists (checks filesystem sockets and Linux abstract sockets) |
|
||||
| uri | URI String |
|
||||
| url | URL String |
|
||||
| http_url | HTTP URL String |
|
||||
| http_url | HTTP(s) URL String |
|
||||
| https_url | HTTPS-only URL String |
|
||||
| origin | Web origin (URL with HTTP(S) scheme and host, but no path/query/fragment) |
|
||||
| url_encoded | URL Encoded |
|
||||
| urn_rfc2141 | Urn RFC 2141 String |
|
||||
| urn_rfc8141 | Urn RFC 8141 String |
|
||||
|
||||
### Strings:
|
||||
|
||||
| Tag | Description |
|
||||
| - | - |
|
||||
| alpha | Alpha Only |
|
||||
| alphaspace | Alpha Space |
|
||||
| alphanum | Alphanumeric |
|
||||
| alphanumspace | Alphanumeric Space |
|
||||
| alphanumunicode | Alphanumeric Unicode |
|
||||
| alphaunicode | Alpha Unicode |
|
||||
| ascii | ASCII |
|
||||
@@ -161,8 +169,10 @@ validate := validator.New(validator.WithRequiredStructEnabled())
|
||||
| base64 | Base64 String |
|
||||
| base64url | Base64URL String |
|
||||
| base64rawurl | Base64RawURL String |
|
||||
| bic | Business Identifier Code (ISO 9362) |
|
||||
| bic_iso_9362_2014 | Business Identifier Code (ISO 9362:2014) |
|
||||
| bic | Business Identifier Code (ISO 9362:2022) |
|
||||
| bcp47_language_tag | Language tag (BCP 47) |
|
||||
| bcp47_strict_language_tag | Language tag (BCP 47), strictly following RFC 5646 |
|
||||
| btc_addr | Bitcoin Address |
|
||||
| btc_addr_bech32 | Bitcoin Bech32 Address (segwit) |
|
||||
| credit_card | Credit Card Number |
|
||||
@@ -171,14 +181,16 @@ validate := validator.New(validator.WithRequiredStructEnabled())
|
||||
| cron | Cron |
|
||||
| spicedb | SpiceDb ObjectID/Permission/Type |
|
||||
| datetime | Datetime |
|
||||
| duration | Duration string (Go time.ParseDuration format) |
|
||||
| e164 | e164 formatted phone number |
|
||||
| ein | U.S. Employeer Identification Number |
|
||||
| ein | U.S. Employer Identification Number |
|
||||
| email | E-mail String
|
||||
| eth_addr | Ethereum Address |
|
||||
| hexadecimal | Hexadecimal String |
|
||||
| hexcolor | Hexcolor String |
|
||||
| hsl | HSL String |
|
||||
| hsla | HSLA String |
|
||||
| cmyk | CMYK String |
|
||||
| html | HTML Tags |
|
||||
| html_encoded | HTML Encoded |
|
||||
| isbn | International Standard Book Number |
|
||||
@@ -215,7 +227,7 @@ validate := validator.New(validator.WithRequiredStructEnabled())
|
||||
| sha384 | SHA384 hash |
|
||||
| sha512 | SHA512 hash |
|
||||
| ripemd128 | RIPEMD-128 hash |
|
||||
| ripemd128 | RIPEMD-160 hash |
|
||||
| ripemd160 | RIPEMD-160 hash |
|
||||
| tiger128 | TIGER128 hash |
|
||||
| tiger160 | TIGER160 hash |
|
||||
| tiger192 | TIGER192 hash |
|
||||
@@ -243,11 +255,13 @@ validate := validator.New(validator.WithRequiredStructEnabled())
|
||||
| file | Existing File |
|
||||
| filepath | File Path |
|
||||
| image | Image |
|
||||
| mimetype | MIME Type |
|
||||
| isdefault | Is Default |
|
||||
| len | Length |
|
||||
| max | Maximum |
|
||||
| min | Minimum |
|
||||
| oneof | One Of |
|
||||
| noneof | None Of |
|
||||
| required | Required |
|
||||
| required_if | Required If |
|
||||
| required_unless | Required Unless |
|
||||
@@ -268,8 +282,9 @@ validate := validator.New(validator.WithRequiredStructEnabled())
|
||||
#### Aliases:
|
||||
| Tag | Description |
|
||||
| - | - |
|
||||
| iscolor | hexcolor\|rgb\|rgba\|hsl\|hsla |
|
||||
| iscolor | hexcolor\|rgb\|rgba\|hsl\|hsla\|cmyk |
|
||||
| country_code | iso3166_1_alpha2\|iso3166_1_alpha3\|iso3166_1_alpha_numeric |
|
||||
| eu_country_code | iso3166_1_alpha2_eu\|iso3166_1_alpha3_eu\|iso3166_1_alpha_numeric_eu |
|
||||
|
||||
Benchmarks
|
||||
------
|
||||
|
||||
+696
-220
File diff suppressed because it is too large.
Load diff
+19
-1
@@ -144,7 +144,7 @@ func (v *Validate) extractStructCache(current reflect.Value, sName string) *cStr
|
||||
|
||||
if v.hasTagNameFunc {
|
||||
name := v.tagNameFunc(fld)
|
||||
if len(name) > 0 {
|
||||
if len(name) > 0 || v.omitBlankFieldNames {
|
||||
customName = name
|
||||
}
|
||||
}
|
||||
@@ -289,6 +289,24 @@ func (v *Validate) parseFieldTagsRecursive(tag string, fieldName string, alias s
|
||||
if wrapper, ok := v.validations[current.tag]; ok {
|
||||
current.fn = wrapper.fn
|
||||
current.runValidationWhenNil = wrapper.runValidationOnNil
|
||||
} else if aliasTag, isAlias := v.aliases[current.tag]; isAlias {
|
||||
aliasFirst, aliasLast := v.parseFieldTagsRecursive(aliasTag, fieldName, current.tag, true)
|
||||
|
||||
current.tag = aliasFirst.tag
|
||||
current.fn = aliasFirst.fn
|
||||
current.runValidationWhenNil = aliasFirst.runValidationWhenNil
|
||||
current.hasParam = aliasFirst.hasParam
|
||||
current.param = aliasFirst.param
|
||||
current.typeof = aliasFirst.typeof
|
||||
current.hasAlias = true
|
||||
|
||||
if aliasFirst.next != nil {
|
||||
nextInChain := current.next
|
||||
current.next = aliasFirst.next
|
||||
aliasLast.next = nextInChain
|
||||
aliasLast.isBlockEnd = false
|
||||
current = aliasLast
|
||||
}
|
||||
} else {
|
||||
panic(strings.TrimSpace(fmt.Sprintf(undefinedValidation, current.tag, fieldName)))
|
||||
}
|
||||
|
||||
+18
-6
@@ -258,7 +258,7 @@ var iso3166_2 = map[string]struct{}{
|
||||
"BD-56": {}, "BD-57": {}, "BD-58": {}, "BD-59": {}, "BD-60": {},
|
||||
"BD-61": {}, "BD-62": {}, "BD-63": {}, "BD-64": {}, "BD-A": {},
|
||||
"BD-B": {}, "BD-C": {}, "BD-D": {}, "BD-E": {}, "BD-F": {},
|
||||
"BD-G": {}, "BE-BRU": {}, "BE-VAN": {}, "BE-VBR": {}, "BE-VLG": {},
|
||||
"BD-G": {}, "BD-H": {}, "BE-BRU": {}, "BE-VAN": {}, "BE-VBR": {}, "BE-VLG": {},
|
||||
"BE-VLI": {}, "BE-VOV": {}, "BE-VWV": {}, "BE-WAL": {}, "BE-WBR": {},
|
||||
"BE-WHT": {}, "BE-WLG": {}, "BE-WLX": {}, "BE-WNA": {}, "BF-01": {},
|
||||
"BF-02": {}, "BF-03": {}, "BF-04": {}, "BF-05": {}, "BF-06": {},
|
||||
@@ -573,7 +573,7 @@ var iso3166_2 = map[string]struct{}{
|
||||
"ID-KB": {}, "ID-KI": {}, "ID-KU": {}, "ID-KR": {}, "ID-KS": {},
|
||||
"ID-KT": {}, "ID-LA": {}, "ID-MA": {}, "ID-ML": {}, "ID-MU": {},
|
||||
"ID-NB": {}, "ID-NT": {}, "ID-NU": {}, "ID-PA": {}, "ID-PB": {},
|
||||
"ID-PE": {}, "ID-PP": {}, "ID-PS": {}, "ID-PT": {}, "ID-RI": {},
|
||||
"ID-PD": {}, "ID-PE": {}, "ID-PP": {}, "ID-PS": {}, "ID-PT": {}, "ID-RI": {},
|
||||
"ID-SA": {}, "ID-SB": {}, "ID-SG": {}, "ID-SL": {}, "ID-SM": {},
|
||||
"ID-SN": {}, "ID-SR": {}, "ID-SS": {}, "ID-ST": {}, "ID-SU": {},
|
||||
"ID-YO": {}, "IE-C": {}, "IE-CE": {}, "IE-CN": {}, "IE-CO": {},
|
||||
@@ -587,7 +587,7 @@ var iso3166_2 = map[string]struct{}{
|
||||
"IN-AS": {}, "IN-BR": {}, "IN-CH": {}, "IN-CT": {}, "IN-DH": {},
|
||||
"IN-DL": {}, "IN-DN": {}, "IN-GA": {}, "IN-GJ": {}, "IN-HP": {},
|
||||
"IN-HR": {}, "IN-JH": {}, "IN-JK": {}, "IN-KA": {}, "IN-KL": {},
|
||||
"IN-LD": {}, "IN-MH": {}, "IN-ML": {}, "IN-MN": {}, "IN-MP": {},
|
||||
"IN-LA": {}, "IN-LD": {}, "IN-MH": {}, "IN-ML": {}, "IN-MN": {}, "IN-MP": {},
|
||||
"IN-MZ": {}, "IN-NL": {}, "IN-TG": {}, "IN-OR": {}, "IN-PB": {}, "IN-PY": {},
|
||||
"IN-RJ": {}, "IN-SK": {}, "IN-TN": {}, "IN-TR": {}, "IN-UP": {},
|
||||
"IN-UT": {}, "IN-WB": {}, "IQ-AN": {}, "IQ-AR": {}, "IQ-BA": {},
|
||||
@@ -667,7 +667,7 @@ var iso3166_2 = map[string]struct{}{
|
||||
"KP-08": {}, "KP-09": {}, "KP-10": {}, "KP-13": {}, "KR-11": {},
|
||||
"KR-26": {}, "KR-27": {}, "KR-28": {}, "KR-29": {}, "KR-30": {},
|
||||
"KR-31": {}, "KR-41": {}, "KR-42": {}, "KR-43": {}, "KR-44": {},
|
||||
"KR-45": {}, "KR-46": {}, "KR-47": {}, "KR-48": {}, "KR-49": {},
|
||||
"KR-45": {}, "KR-46": {}, "KR-47": {}, "KR-48": {}, "KR-49": {}, "KR-50": {},
|
||||
"KW-AH": {}, "KW-FA": {}, "KW-HA": {}, "KW-JA": {}, "KW-KU": {},
|
||||
"KW-MU": {}, "KZ-10": {}, "KZ-75": {}, "KZ-19": {}, "KZ-11": {},
|
||||
"KZ-15": {}, "KZ-71": {}, "KZ-23": {}, "KZ-27": {}, "KZ-47": {},
|
||||
@@ -758,7 +758,7 @@ var iso3166_2 = map[string]struct{}{
|
||||
"ME-02": {}, "ME-03": {}, "ME-04": {}, "ME-05": {}, "ME-06": {},
|
||||
"ME-07": {}, "ME-08": {}, "ME-09": {}, "ME-10": {}, "ME-11": {},
|
||||
"ME-12": {}, "ME-13": {}, "ME-14": {}, "ME-15": {}, "ME-16": {},
|
||||
"ME-17": {}, "ME-18": {}, "ME-19": {}, "ME-20": {}, "ME-21": {}, "ME-24": {},
|
||||
"ME-17": {}, "ME-18": {}, "ME-19": {}, "ME-20": {}, "ME-21": {}, "ME-22": {}, "ME-23": {}, "ME-24": {}, "ME-25": {},
|
||||
"MG-A": {}, "MG-D": {}, "MG-F": {}, "MG-M": {}, "MG-T": {},
|
||||
"MG-U": {}, "MH-ALK": {}, "MH-ALL": {}, "MH-ARN": {}, "MH-AUR": {},
|
||||
"MH-EBO": {}, "MH-ENI": {}, "MH-JAB": {}, "MH-JAL": {}, "MH-KIL": {},
|
||||
@@ -856,7 +856,7 @@ var iso3166_2 = map[string]struct{}{
|
||||
"NO-22": {}, "NP-1": {}, "NP-2": {}, "NP-3": {}, "NP-4": {},
|
||||
"NP-5": {}, "NP-BA": {}, "NP-BH": {}, "NP-DH": {}, "NP-GA": {},
|
||||
"NP-JA": {}, "NP-KA": {}, "NP-KO": {}, "NP-LU": {}, "NP-MA": {},
|
||||
"NP-ME": {}, "NP-NA": {}, "NP-RA": {}, "NP-SA": {}, "NP-SE": {},
|
||||
"NP-ME": {}, "NP-NA": {}, "NP-P1": {}, "NP-P2": {}, "NP-P3": {}, "NP-P4": {}, "NP-P5": {}, "NP-P6": {}, "NP-P7": {}, "NP-RA": {}, "NP-SA": {}, "NP-SE": {},
|
||||
"NR-01": {}, "NR-02": {}, "NR-03": {}, "NR-04": {}, "NR-05": {},
|
||||
"NR-06": {}, "NR-07": {}, "NR-08": {}, "NR-09": {}, "NR-10": {},
|
||||
"NR-11": {}, "NR-12": {}, "NR-13": {}, "NR-14": {}, "NZ-AUK": {},
|
||||
@@ -1175,3 +1175,15 @@ var iso3166_2 = map[string]struct{}{
|
||||
"ZW-BU": {}, "ZW-HA": {}, "ZW-MA": {}, "ZW-MC": {}, "ZW-ME": {},
|
||||
"ZW-MI": {}, "ZW-MN": {}, "ZW-MS": {}, "ZW-MV": {}, "ZW-MW": {},
|
||||
}
|
||||
|
||||
// Subset of UN M.49 region codes present in the IANA Language Subtag Registry:
|
||||
// https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
|
||||
var iana_subtag_registry_m49_codes = map[string]struct{}{
|
||||
"001": {}, "002": {}, "003": {}, "005": {}, "009": {},
|
||||
"011": {}, "013": {}, "014": {}, "015": {}, "017": {},
|
||||
"018": {}, "019": {}, "021": {}, "029": {}, "030": {},
|
||||
"034": {}, "035": {}, "039": {}, "053": {}, "054": {},
|
||||
"057": {}, "061": {}, "142": {}, "143": {}, "145": {},
|
||||
"150": {}, "151": {}, "154": {}, "155": {}, "202": {},
|
||||
"419": {},
|
||||
}
|
||||
+58
-58
@@ -10,33 +10,33 @@ var iso4217 = map[string]struct{}{
|
||||
"BIF": {}, "CVE": {}, "KHR": {}, "XAF": {}, "CAD": {},
|
||||
"KYD": {}, "CLP": {}, "CLF": {}, "CNY": {}, "COP": {},
|
||||
"COU": {}, "KMF": {}, "CDF": {}, "NZD": {}, "CRC": {},
|
||||
"HRK": {}, "CUP": {}, "CUC": {}, "ANG": {}, "CZK": {},
|
||||
"DKK": {}, "DJF": {}, "DOP": {}, "EGP": {}, "SVC": {},
|
||||
"ERN": {}, "SZL": {}, "ETB": {}, "FKP": {}, "FJD": {},
|
||||
"XPF": {}, "GMD": {}, "GEL": {}, "GHS": {}, "GIP": {},
|
||||
"GTQ": {}, "GBP": {}, "GNF": {}, "GYD": {}, "HTG": {},
|
||||
"HNL": {}, "HKD": {}, "HUF": {}, "ISK": {}, "IDR": {},
|
||||
"XDR": {}, "IRR": {}, "IQD": {}, "ILS": {}, "JMD": {},
|
||||
"JPY": {}, "JOD": {}, "KZT": {}, "KES": {}, "KPW": {},
|
||||
"KRW": {}, "KWD": {}, "KGS": {}, "LAK": {}, "LBP": {},
|
||||
"LSL": {}, "ZAR": {}, "LRD": {}, "LYD": {}, "CHF": {},
|
||||
"MOP": {}, "MKD": {}, "MGA": {}, "MWK": {}, "MYR": {},
|
||||
"MVR": {}, "MRU": {}, "MUR": {}, "XUA": {}, "MXN": {},
|
||||
"MXV": {}, "MDL": {}, "MNT": {}, "MAD": {}, "MZN": {},
|
||||
"MMK": {}, "NAD": {}, "NPR": {}, "NIO": {}, "NGN": {},
|
||||
"OMR": {}, "PKR": {}, "PAB": {}, "PGK": {}, "PYG": {},
|
||||
"PEN": {}, "PHP": {}, "PLN": {}, "QAR": {}, "RON": {},
|
||||
"RUB": {}, "RWF": {}, "SHP": {}, "WST": {}, "STN": {},
|
||||
"SAR": {}, "RSD": {}, "SCR": {}, "SLL": {}, "SGD": {},
|
||||
"XSU": {}, "SBD": {}, "SOS": {}, "SSP": {}, "LKR": {},
|
||||
"SDG": {}, "SRD": {}, "SEK": {}, "CHE": {}, "CHW": {},
|
||||
"SYP": {}, "TWD": {}, "TJS": {}, "TZS": {}, "THB": {},
|
||||
"TOP": {}, "TTD": {}, "TND": {}, "TRY": {}, "TMT": {},
|
||||
"UGX": {}, "UAH": {}, "AED": {}, "USN": {}, "UYU": {},
|
||||
"UYI": {}, "UYW": {}, "UZS": {}, "VUV": {}, "VES": {},
|
||||
"VND": {}, "YER": {}, "ZMW": {}, "ZWL": {}, "XBA": {},
|
||||
"XBB": {}, "XBC": {}, "XBD": {}, "XTS": {}, "XXX": {},
|
||||
"XAU": {}, "XPD": {}, "XPT": {}, "XAG": {},
|
||||
"CUP": {}, "CZK": {}, "DKK": {}, "DJF": {}, "DOP": {},
|
||||
"EGP": {}, "SVC": {}, "ERN": {}, "SZL": {}, "ETB": {},
|
||||
"FKP": {}, "FJD": {}, "XPF": {}, "GMD": {}, "GEL": {},
|
||||
"GHS": {}, "GIP": {}, "GTQ": {}, "GBP": {}, "GNF": {},
|
||||
"GYD": {}, "HTG": {}, "HNL": {}, "HKD": {}, "HUF": {},
|
||||
"ISK": {}, "IDR": {}, "XDR": {}, "IRR": {}, "IQD": {},
|
||||
"ILS": {}, "JMD": {}, "JPY": {}, "JOD": {}, "KZT": {},
|
||||
"KES": {}, "KPW": {}, "KRW": {}, "KWD": {}, "KGS": {},
|
||||
"LAK": {}, "LBP": {}, "LSL": {}, "ZAR": {}, "LRD": {},
|
||||
"LYD": {}, "CHF": {}, "MOP": {}, "MKD": {}, "MGA": {},
|
||||
"MWK": {}, "MYR": {}, "MVR": {}, "MRU": {}, "MUR": {},
|
||||
"XUA": {}, "MXN": {}, "MXV": {}, "MDL": {}, "MNT": {},
|
||||
"MAD": {}, "MZN": {}, "MMK": {}, "NAD": {}, "NPR": {},
|
||||
"NIO": {}, "NGN": {}, "OMR": {}, "PKR": {}, "PAB": {},
|
||||
"PGK": {}, "PYG": {}, "PEN": {}, "PHP": {}, "PLN": {},
|
||||
"QAR": {}, "RON": {}, "RUB": {}, "RWF": {}, "SHP": {},
|
||||
"WST": {}, "STN": {}, "SAR": {}, "RSD": {}, "SCR": {},
|
||||
"SLE": {}, "SGD": {}, "XSU": {}, "SBD": {}, "SOS": {},
|
||||
"SSP": {}, "LKR": {}, "SDG": {}, "SRD": {}, "SEK": {},
|
||||
"CHE": {}, "CHW": {}, "SYP": {}, "TWD": {}, "TJS": {},
|
||||
"TZS": {}, "THB": {}, "TOP": {}, "TTD": {}, "TND": {},
|
||||
"TRY": {}, "TMT": {}, "UGX": {}, "UAH": {}, "AED": {},
|
||||
"USN": {}, "UYU": {}, "UYI": {}, "UYW": {}, "UZS": {},
|
||||
"VUV": {}, "VES": {}, "VED": {}, "VND": {}, "YER": {},
|
||||
"ZMW": {}, "ZWG": {}, "XBA": {}, "XBB": {}, "XBC": {},
|
||||
"XBD": {}, "XCG": {}, "XTS": {}, "XXX": {}, "XAU": {},
|
||||
"XPD": {}, "XPT": {}, "XAG": {},
|
||||
}
|
||||
|
||||
var iso4217_numeric = map[int]struct{}{
|
||||
@@ -45,35 +45,35 @@ var iso4217_numeric = map[int]struct{}{
|
||||
64: {}, 68: {}, 72: {}, 84: {}, 90: {},
|
||||
96: {}, 104: {}, 108: {}, 116: {}, 124: {},
|
||||
132: {}, 136: {}, 144: {}, 152: {}, 156: {},
|
||||
170: {}, 174: {}, 188: {}, 191: {}, 192: {},
|
||||
203: {}, 208: {}, 214: {}, 222: {}, 230: {},
|
||||
232: {}, 238: {}, 242: {}, 262: {}, 270: {},
|
||||
292: {}, 320: {}, 324: {}, 328: {}, 332: {},
|
||||
340: {}, 344: {}, 348: {}, 352: {}, 356: {},
|
||||
360: {}, 364: {}, 368: {}, 376: {}, 388: {},
|
||||
392: {}, 398: {}, 400: {}, 404: {}, 408: {},
|
||||
410: {}, 414: {}, 417: {}, 418: {}, 422: {},
|
||||
426: {}, 430: {}, 434: {}, 446: {}, 454: {},
|
||||
458: {}, 462: {}, 480: {}, 484: {}, 496: {},
|
||||
498: {}, 504: {}, 512: {}, 516: {}, 524: {},
|
||||
532: {}, 533: {}, 548: {}, 554: {}, 558: {},
|
||||
566: {}, 578: {}, 586: {}, 590: {}, 598: {},
|
||||
600: {}, 604: {}, 608: {}, 634: {}, 643: {},
|
||||
646: {}, 654: {}, 682: {}, 690: {}, 694: {},
|
||||
702: {}, 704: {}, 706: {}, 710: {}, 728: {},
|
||||
748: {}, 752: {}, 756: {}, 760: {}, 764: {},
|
||||
776: {}, 780: {}, 784: {}, 788: {}, 800: {},
|
||||
807: {}, 818: {}, 826: {}, 834: {}, 840: {},
|
||||
858: {}, 860: {}, 882: {}, 886: {}, 901: {},
|
||||
927: {}, 928: {}, 929: {}, 930: {}, 931: {},
|
||||
932: {}, 933: {}, 934: {}, 936: {}, 938: {},
|
||||
940: {}, 941: {}, 943: {}, 944: {}, 946: {},
|
||||
947: {}, 948: {}, 949: {}, 950: {}, 951: {},
|
||||
952: {}, 953: {}, 955: {}, 956: {}, 957: {},
|
||||
958: {}, 959: {}, 960: {}, 961: {}, 962: {},
|
||||
963: {}, 964: {}, 965: {}, 967: {}, 968: {},
|
||||
969: {}, 970: {}, 971: {}, 972: {}, 973: {},
|
||||
975: {}, 976: {}, 977: {}, 978: {}, 979: {},
|
||||
980: {}, 981: {}, 984: {}, 985: {}, 986: {},
|
||||
990: {}, 994: {}, 997: {}, 999: {},
|
||||
170: {}, 174: {}, 188: {}, 192: {}, 203: {},
|
||||
208: {}, 214: {}, 222: {}, 230: {}, 232: {},
|
||||
238: {}, 242: {}, 262: {}, 270: {}, 292: {},
|
||||
320: {}, 324: {}, 328: {}, 332: {}, 340: {},
|
||||
344: {}, 348: {}, 352: {}, 356: {}, 360: {},
|
||||
364: {}, 368: {}, 376: {}, 388: {}, 392: {},
|
||||
398: {}, 400: {}, 404: {}, 408: {}, 410: {},
|
||||
414: {}, 417: {}, 418: {}, 422: {}, 426: {},
|
||||
430: {}, 434: {}, 446: {}, 454: {}, 458: {},
|
||||
462: {}, 480: {}, 484: {}, 496: {}, 498: {},
|
||||
504: {}, 512: {}, 516: {}, 524: {}, 532: {},
|
||||
533: {}, 548: {}, 554: {}, 558: {}, 566: {},
|
||||
578: {}, 586: {}, 590: {}, 598: {}, 600: {},
|
||||
604: {}, 608: {}, 634: {}, 643: {}, 646: {},
|
||||
654: {}, 682: {}, 690: {}, 702: {}, 704: {},
|
||||
706: {}, 710: {}, 728: {}, 748: {}, 752: {},
|
||||
756: {}, 760: {}, 764: {}, 776: {}, 780: {},
|
||||
784: {}, 788: {}, 800: {}, 807: {}, 818: {},
|
||||
826: {}, 834: {}, 840: {}, 858: {}, 860: {},
|
||||
882: {}, 886: {}, 901: {}, 924: {}, 925: {},
|
||||
926: {}, 927: {}, 928: {}, 929: {}, 930: {},
|
||||
933: {}, 934: {}, 936: {}, 938: {}, 940: {},
|
||||
941: {}, 943: {}, 944: {}, 946: {}, 947: {},
|
||||
948: {}, 949: {}, 950: {}, 951: {}, 952: {},
|
||||
953: {}, 955: {}, 956: {}, 957: {}, 958: {},
|
||||
959: {}, 960: {}, 961: {}, 962: {}, 963: {},
|
||||
964: {}, 965: {}, 967: {}, 968: {}, 969: {},
|
||||
970: {}, 971: {}, 972: {}, 973: {}, 975: {},
|
||||
976: {}, 977: {}, 978: {}, 979: {}, 980: {},
|
||||
981: {}, 984: {}, 985: {}, 986: {}, 990: {},
|
||||
994: {}, 997: {}, 999: {},
|
||||
}
|
||||
+174
-22
@@ -52,6 +52,40 @@ Custom Validation functions can be added. Example:
|
||||
// NOTES: using the same tag name as an existing function
|
||||
// will overwrite the existing one
|
||||
|
||||
# Valuer Interface
|
||||
|
||||
Custom types can implement the Valuer interface to return the value that should
|
||||
be validated. This is useful when a type wraps another value and you want
|
||||
validation to run against the unwrapped value.
|
||||
|
||||
type Nullable[T any] struct {
|
||||
Data T
|
||||
}
|
||||
|
||||
func (n Nullable[T]) ValidatorValue() any {
|
||||
return n.Data
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Name string `validate:"required"`
|
||||
}
|
||||
|
||||
type Record struct {
|
||||
Config Nullable[Config] `validate:"required"`
|
||||
}
|
||||
|
||||
r := Record{
|
||||
Config: Nullable[Config]{
|
||||
Data: Config{Name: "validator"},
|
||||
},
|
||||
}
|
||||
|
||||
err := validate.Struct(r)
|
||||
|
||||
The library also supports types like sql/driver.Valuer using
|
||||
RegisterCustomTypeFunc. See _examples/valuer/main.go and
|
||||
_examples/custom/main.go for both approaches.
|
||||
|
||||
# Cross-Field Validation
|
||||
|
||||
Cross-Field Validation can be done via the following tags:
|
||||
@@ -104,7 +138,7 @@ used "eqcsfield" it could be multiple levels down. Example:
|
||||
// into the function
|
||||
// when calling validate.VarWithValue(val, field, tag) val will be
|
||||
// whatever you pass, struct, field...
|
||||
// when calling validate.Field(field, tag) val will be nil
|
||||
// when calling validate.Var(field, tag) val will be the field itself
|
||||
|
||||
# Multiple Validators
|
||||
|
||||
@@ -150,6 +184,12 @@ so the above will become excludesall=0x7C
|
||||
Field `validate:"excludesall=0x7C"` // GOOD! Use the UTF-8 hex representation.
|
||||
}
|
||||
|
||||
# Build tags
|
||||
|
||||
The library provides a build tag for build size optimizations. If you are not using
|
||||
`validateFn` you can add the `validator_novalidatefn` build tag to enabled better dead
|
||||
code elimination. With this build tag, any usage of `validateFn` tags will panic.
|
||||
|
||||
# Baked In Validators and Tags
|
||||
|
||||
Here is a list of the current built in validators:
|
||||
@@ -188,7 +228,7 @@ Same as structonly tag except that any struct level validations will not run.
|
||||
|
||||
# Omit Empty
|
||||
|
||||
Allows conditional validation, for example if a field is not set with
|
||||
Allows conditional validation, for example, if a field is not set with
|
||||
a value (Determined by the "required" validator) then other validation
|
||||
such as min or max won't run, but if a value is set validation will run.
|
||||
|
||||
@@ -201,6 +241,15 @@ only for the nil-values).
|
||||
|
||||
Usage: omitnil
|
||||
|
||||
# Omit Zero
|
||||
|
||||
Allows to skip the validation if the value is a zero value.
|
||||
For pointers, it checks if the pointer is nil or the underlying value is a zero value.
|
||||
For slices and maps, it checks if the value is nil or empty.
|
||||
Otherwise, behaves the same as omitempty.
|
||||
|
||||
Usage: omitzero
|
||||
|
||||
# Dive
|
||||
|
||||
This tells the validator to dive into a slice, array or map and validate that
|
||||
@@ -264,6 +313,7 @@ The field under validation must be present and not empty only if all
|
||||
the other specified fields are equal to the value following the specified
|
||||
field. For strings ensures value is not "". For slices, maps, pointers,
|
||||
interfaces, channels and functions ensures the value is not nil. For structs ensures value is not the zero value.
|
||||
Using the same field name multiple times in the parameters will result in a panic at runtime.
|
||||
|
||||
Usage: required_if
|
||||
|
||||
@@ -502,6 +552,23 @@ Works the same as oneof but is case insensitive and therefore only accepts strin
|
||||
Usage: oneofci=red green
|
||||
oneofci='red green' 'blue yellow'
|
||||
|
||||
# None Of
|
||||
|
||||
For strings, ints, and uints, noneof will ensure that the value is not one of
|
||||
the values in the parameter. The parameter should be a list of values separated by whitespace.
|
||||
Values may be strings or numbers. To inversely match strings with spaces in them, include the target string between single quotes.
|
||||
Kind of like an 'enum'.
|
||||
|
||||
Usage: noneof=red green
|
||||
noneof='red green' 'blue yellow'
|
||||
noneof=5 7 9
|
||||
|
||||
# None Of Case Insensitive
|
||||
Works the same as noneof but is case insensitive and therefore only accepts strings.
|
||||
|
||||
Usage: noneofci=red green
|
||||
noneofci='red green' 'blue yellow'
|
||||
|
||||
# Greater Than
|
||||
|
||||
For numbers, this will ensure that the value is greater than the
|
||||
@@ -733,15 +800,16 @@ This does the same as contains except for struct fields. It should only be used
|
||||
with string types. See the behavior of reflect.Value.String() for behavior on
|
||||
other types.
|
||||
|
||||
Usage: containsfield=InnerStructField.Field
|
||||
Usage: fieldcontains=InnerStructField.Field
|
||||
|
||||
# Field Excludes Another Field
|
||||
# Field Excludes Another Field's Value
|
||||
|
||||
This does the same as excludes except for struct fields. It should only be used
|
||||
with string types. See the behavior of reflect.Value.String() for behavior on
|
||||
other types.
|
||||
This validates that the current field's string value does not contain the
|
||||
string value of the field named by the parameter. It should only be used with
|
||||
string types. If the referenced field cannot be resolved, validation succeeds.
|
||||
See the behavior of reflect.Value.String() for behavior on other types.
|
||||
|
||||
Usage: excludesfield=InnerStructField.Field
|
||||
Usage: fieldexcludes=InnerStructField.Field
|
||||
|
||||
# Unique
|
||||
|
||||
@@ -776,12 +844,24 @@ This validates that a string value contains ASCII alpha characters only
|
||||
|
||||
Usage: alpha
|
||||
|
||||
# Alpha Space
|
||||
|
||||
This validates that a string value contains ASCII alpha characters and spaces only
|
||||
|
||||
Usage: alphaspace
|
||||
|
||||
# Alphanumeric
|
||||
|
||||
This validates that a string value contains ASCII alphanumeric characters only
|
||||
|
||||
Usage: alphanum
|
||||
|
||||
# Alphanumeric Space
|
||||
|
||||
This validates that a string value contains ASCII alphanumeric characters and spaces only
|
||||
|
||||
Usage: alphanumspace
|
||||
|
||||
# Alpha Unicode
|
||||
|
||||
This validates that a string value contains unicode alpha characters only
|
||||
@@ -864,6 +944,12 @@ This validates that a string value contains a valid hsla color
|
||||
|
||||
Usage: hsla
|
||||
|
||||
# CMYK String
|
||||
|
||||
This validates that a string value contains a valid cmyk color
|
||||
|
||||
Usage: cmyk
|
||||
|
||||
# E.164 Phone Number String
|
||||
|
||||
This validates that a string value contains a valid E.164 Phone number
|
||||
@@ -907,6 +993,16 @@ This is done using os.Stat and github.com/gabriel-vasile/mimetype
|
||||
|
||||
Usage: image
|
||||
|
||||
# MIME type path
|
||||
|
||||
This validates that a string value contains a valid file path and that
|
||||
the file exists on the machine and matches the provided MIME type in the
|
||||
form type/subtype or type/*.
|
||||
This is done using os.Stat and github.com/gabriel-vasile/mimetype
|
||||
|
||||
Usage: mimetype=image/png
|
||||
Usage: mimetype=image/*
|
||||
|
||||
# File Path
|
||||
|
||||
This validates that a string value contains a valid file path but does not
|
||||
@@ -930,6 +1026,13 @@ This will accept any uri the golang request uri accepts
|
||||
|
||||
Usage: uri
|
||||
|
||||
# Urn RFC 8141 String
|
||||
|
||||
This validataes that a string value contains a valid URN
|
||||
according to the RFC 8141 spec.
|
||||
|
||||
Usage: urn_rfc8141
|
||||
|
||||
# Urn RFC 2141 String
|
||||
|
||||
This validates that a string value contains a valid URN
|
||||
@@ -1080,7 +1183,7 @@ This validates that a string value contains a valid isbn13 value.
|
||||
|
||||
# Universally Unique Identifier UUID
|
||||
|
||||
This validates that a string value contains a valid UUID. Uppercase UUID values will not pass - use `uuid_rfc4122` instead.
|
||||
This validates that a string value contains a valid UUID. Both lowercase and uppercase hex digits are accepted.
|
||||
|
||||
Usage: uuid
|
||||
|
||||
@@ -1148,7 +1251,7 @@ This validates that a string value contains a valid longitude.
|
||||
|
||||
Usage: longitude
|
||||
|
||||
# Employeer Identification Number EIN
|
||||
# Employer Identification Number EIN
|
||||
|
||||
This validates that a string value contains a valid U.S. Employer Identification Number.
|
||||
|
||||
@@ -1256,6 +1359,15 @@ This validates that a string value contains a valid Unix Address.
|
||||
|
||||
Usage: unix_addr
|
||||
|
||||
# Unix Domain Socket Exists
|
||||
|
||||
This validates that a Unix domain socket file exists at the specified path.
|
||||
It checks both filesystem-based sockets and Linux abstract sockets (prefixed with @).
|
||||
For filesystem sockets, it verifies the path exists and is a socket file.
|
||||
For abstract sockets on Linux, it checks /proc/net/unix.
|
||||
|
||||
Usage: uds_exists
|
||||
|
||||
# Media Access Control Address MAC
|
||||
|
||||
This validates that a string value contains a valid MAC Address.
|
||||
@@ -1278,6 +1390,13 @@ This validates that a string value is a valid Hostname according to RFC 1123 htt
|
||||
|
||||
Usage: hostname_rfc1123 or if you want to continue to use 'hostname' in your tags, create an alias.
|
||||
|
||||
# Hostname Label
|
||||
|
||||
This validates that a string value is a valid hostname label (The 'label' in 'label.domain.name') according to
|
||||
RFC 1123 https://tools.ietf.org/rfc1123.
|
||||
|
||||
Usage: hostname_label
|
||||
|
||||
Full Qualified Domain Name (FQDN)
|
||||
|
||||
This validates that a string value contains a valid FQDN.
|
||||
@@ -1315,11 +1434,13 @@ This is done using os.Stat, which is a platform independent function.
|
||||
|
||||
# Directory Path
|
||||
|
||||
This validates that a string value contains a valid directory but does
|
||||
not validate the existence of that directory.
|
||||
This is done using os.Stat, which is a platform independent function.
|
||||
It is safest to suffix the string with os.PathSeparator if the directory
|
||||
may not exist at the time of validation.
|
||||
This validates that a string value contains a valid directory path without
|
||||
requiring the directory to exist. An existing directory is accepted with or
|
||||
without a trailing separator, as determined by os.Stat.
|
||||
If the directory does not exist, the path must end with os.PathSeparator;
|
||||
otherwise it is rejected because it cannot be distinguished from a file path.
|
||||
For example, filepath.Join("parent", "new-directory") + string(os.PathSeparator)
|
||||
can be used to validate a directory path before creating it.
|
||||
|
||||
Usage: dirpath
|
||||
|
||||
@@ -1330,6 +1451,12 @@ can be used to validate fields typically passed to sockets and connections.
|
||||
|
||||
Usage: hostname_port
|
||||
|
||||
# Port
|
||||
|
||||
This validates that an integer value (signed or unsigned) falls within the valid port range of 1-65,535.
|
||||
|
||||
Usage: port
|
||||
|
||||
# Datetime
|
||||
|
||||
This validates that a string value is a valid datetime based on the supplied datetime format.
|
||||
@@ -1337,6 +1464,14 @@ Supplied format must match the official Go time format layout as documented in h
|
||||
|
||||
Usage: datetime=2006-01-02
|
||||
|
||||
# Duration
|
||||
|
||||
This validates that a string value is a valid duration as accepted by time.ParseDuration,
|
||||
such as "300ms", "-1.5h" or "2h45m". Non-string fields, including time.Duration, fail validation.
|
||||
see: https://pkg.go.dev/time#ParseDuration
|
||||
|
||||
Usage: duration
|
||||
|
||||
# Iso3166-1 alpha-2
|
||||
|
||||
This validates that a string value is a valid country code based on iso3166-1 alpha-2 standard.
|
||||
@@ -1365,13 +1500,28 @@ More information on https://pkg.go.dev/golang.org/x/text/language
|
||||
|
||||
Usage: bcp47_language_tag
|
||||
|
||||
BIC (SWIFT code)
|
||||
# BCP 47 Strict Language Tag
|
||||
|
||||
This validates that a string value is a valid Business Identifier Code (SWIFT code), defined in ISO 9362.
|
||||
More information on https://www.iso.org/standard/60390.html
|
||||
This validates that a string value is a valid BCP 47 language tag strictly following RFC 5646 rules,
|
||||
unlike language.Parse which also accepts Unicode extensions.
|
||||
see https://www.rfc-editor.org/rfc/bcp/bcp47.txt
|
||||
|
||||
Usage: bcp47_strict_language_tag
|
||||
|
||||
BIC (SWIFT code - 2022 standard)
|
||||
|
||||
This validates that a string value is a valid Business Identifier Code (SWIFT code), defined in ISO 9362:2022.
|
||||
More information on https://www.iso.org/standard/84108.html
|
||||
|
||||
Usage: bic
|
||||
|
||||
BIC (SWIFT code - 2014 standard)
|
||||
|
||||
This validates that a string value is a valid Business Identifier Code (SWIFT code), defined in ISO 9362:2014.
|
||||
More information on https://www.iso.org/standard/60390.html
|
||||
|
||||
Usage: bic_iso_9362_2014
|
||||
|
||||
# RFC 1035 label
|
||||
|
||||
This validates that a string value is a valid dns RFC 1035 label, defined in RFC 1035.
|
||||
@@ -1450,9 +1600,11 @@ case will be the actual tag within the alias that failed.
|
||||
Here is a list of the current built in alias tags:
|
||||
|
||||
"iscolor"
|
||||
alias is "hexcolor|rgb|rgba|hsl|hsla" (Usage: iscolor)
|
||||
alias is "hexcolor|rgb|rgba|hsl|hsla|cmyk" (Usage: iscolor)
|
||||
"country_code"
|
||||
alias is "iso3166_1_alpha2|iso3166_1_alpha3|iso3166_1_alpha_numeric" (Usage: country_code)
|
||||
"eu_country_code"
|
||||
alias is "iso3166_1_alpha2_eu|iso3166_1_alpha3_eu|iso3166_1_alpha_numeric_eu" (Usage: eu_country_code)
|
||||
|
||||
Validator notes:
|
||||
|
||||
@@ -1485,7 +1637,7 @@ Example of registration and use:
|
||||
}
|
||||
|
||||
t := &Test{
|
||||
TestField: "Test"
|
||||
TestField: "Test",
|
||||
}
|
||||
|
||||
validate := validator.New()
|
||||
@@ -1506,11 +1658,11 @@ This package panics when bad input is provided, this is by design, bad code like
|
||||
that should not make it to production.
|
||||
|
||||
type Test struct {
|
||||
TestField string `validate:"nonexistantfunction=1"`
|
||||
TestField string `validate:"nonexistentfunction=1"`
|
||||
}
|
||||
|
||||
t := &Test{
|
||||
TestField: "Test"
|
||||
TestField: "Test",
|
||||
}
|
||||
|
||||
validate.Struct(t) // this will panic
|
||||
|
||||
+7
-7
@@ -79,7 +79,7 @@ type FieldError interface {
|
||||
// validation was an alias, this will return the
|
||||
// alias name and not the underlying tag that failed.
|
||||
//
|
||||
// eg. alias "iscolor": "hexcolor|rgb|rgba|hsl|hsla"
|
||||
// eg. alias "iscolor": "hexcolor|rgb|rgba|hsl|hsla|cmyk"
|
||||
// will return "iscolor"
|
||||
Tag() string
|
||||
|
||||
@@ -87,8 +87,8 @@ type FieldError interface {
|
||||
// alias the actual tag within the alias will be returned.
|
||||
// If an 'or' validation fails the entire or will be returned.
|
||||
//
|
||||
// eg. alias "iscolor": "hexcolor|rgb|rgba|hsl|hsla"
|
||||
// will return "hexcolor|rgb|rgba|hsl|hsla"
|
||||
// eg. alias "iscolor": "hexcolor|rgb|rgba|hsl|hsla|cmyk"
|
||||
// will return "hexcolor|rgb|rgba|hsl|hsla|cmyk"
|
||||
ActualTag() string
|
||||
|
||||
// Namespace returns the namespace for the field error, with the tag
|
||||
@@ -105,24 +105,24 @@ type FieldError interface {
|
||||
// StructNamespace returns the namespace for the field error, with the field's
|
||||
// actual name.
|
||||
//
|
||||
// eq. "User.FirstName" see Namespace for comparison
|
||||
// eg. "User.FirstName" see Namespace for comparison
|
||||
//
|
||||
// NOTE: this field can be blank when validating a single primitive field
|
||||
// using validate.Field(...) as there is no way to extract its name
|
||||
StructNamespace() string
|
||||
|
||||
// Field returns the fields name with the tag name taking precedence over the
|
||||
// Field returns the field's name with the tag name taking precedence over the
|
||||
// field's actual name.
|
||||
//
|
||||
// `RegisterTagNameFunc` must be registered to get tag value.
|
||||
//
|
||||
// eq. JSON name "fname"
|
||||
// eg. JSON name "fname"
|
||||
// see StructField for comparison
|
||||
Field() string
|
||||
|
||||
// StructField returns the field's actual name from the struct, when able to determine.
|
||||
//
|
||||
// eq. "FirstName"
|
||||
// eg. "FirstName"
|
||||
// see Field for comparison
|
||||
StructField() string
|
||||
|
||||
|
||||
+403
@@ -0,0 +1,403 @@
|
||||
package validator
|
||||
|
||||
// Type: variant and their associated primary language prefixes from the
|
||||
// IANA Language Subtag Registry:
|
||||
// https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
|
||||
var iana_subtag_registry_variants = map[string][]string{
|
||||
"1606nict": {"frm"},
|
||||
"1694acad": {"fr"},
|
||||
"1901": {"de"},
|
||||
"1959acad": {"be"},
|
||||
"1994": {"sl-rozaj", "sl-rozaj-biske", "sl-rozaj-njiva", "sl-rozaj-osojs", "sl-rozaj-solba"},
|
||||
"1996": {"de"},
|
||||
"abl1943": {"pt-BR"},
|
||||
"akhmimic": {"cop"},
|
||||
"akuapem": {"tw"},
|
||||
"alalc97": {},
|
||||
"aluku": {"djk"},
|
||||
"anpezo": {"lld"},
|
||||
"ao1990": {"pt", "gl"},
|
||||
"aranes": {"oc"},
|
||||
"arevela": {"hy"},
|
||||
"arevmda": {"hy"},
|
||||
"arkaika": {"eo"},
|
||||
"asante": {"tw"},
|
||||
"auvern": {"oc"},
|
||||
"baku1926": {"az", "ba", "crh", "kk", "krc", "ky", "sah", "tk", "tt", "uz"},
|
||||
"balanka": {"blo"},
|
||||
"barla": {"kea"},
|
||||
"basiceng": {"en"},
|
||||
"bauddha": {"sa"},
|
||||
"bciav": {"zbl"},
|
||||
"bcizbl": {"zbl"},
|
||||
"biscayan": {"eu"},
|
||||
"biske": {"sl-rozaj"},
|
||||
"blasl": {"ase", "sgn-ase"},
|
||||
"bohairic": {"cop"},
|
||||
"bohoric": {"sl"},
|
||||
"boont": {"en"},
|
||||
"bornholm": {"da"},
|
||||
"cisaup": {"oc"},
|
||||
"colb1945": {"pt"},
|
||||
"cornu": {"en"},
|
||||
"creiss": {"oc"},
|
||||
"dajnko": {"sl"},
|
||||
"ekavsk": {"sr", "sr-Latn", "sr-Cyrl"},
|
||||
"emodeng": {"en"},
|
||||
"fascia": {"lld"},
|
||||
"fayyumic": {"cop"},
|
||||
"fodom": {"lld"},
|
||||
"fonipa": {},
|
||||
"fonkirsh": {},
|
||||
"fonnapa": {},
|
||||
"fonupa": {},
|
||||
"fonxsamp": {},
|
||||
"gallo": {"fr"},
|
||||
"gascon": {"oc"},
|
||||
"gherd": {"lld"},
|
||||
"grclass": {"oc", "oc-aranes", "oc-auvern", "oc-cisaup", "oc-creiss", "oc-gascon", "oc-lemosin", "oc-lengadoc", "oc-nicard", "oc-provenc", "oc-vivaraup"},
|
||||
"grital": {"oc", "oc-cisaup", "oc-nicard", "oc-provenc"},
|
||||
"grmistr": {"oc", "oc-aranes", "oc-auvern", "oc-cisaup", "oc-creiss", "oc-gascon", "oc-lemosin", "oc-lengadoc", "oc-nicard", "oc-provenc", "oc-vivaraup"},
|
||||
"hanoi": {"vi"},
|
||||
"hepburn": {"ja-Latn"},
|
||||
"heploc": {"ja-Latn-hepburn"},
|
||||
"hognorsk": {"nn"},
|
||||
"hsistemo": {"eo"},
|
||||
"huett": {"vi"},
|
||||
"ijekavsk": {"sr", "sr-Latn", "sr-Cyrl"},
|
||||
"itihasa": {"sa"},
|
||||
"ivanchov": {"bg"},
|
||||
"jauer": {"rm"},
|
||||
"jyutping": {"yue"},
|
||||
"kkcor": {"kw"},
|
||||
"kleinsch": {"kl", "kl-tunumiit"},
|
||||
"kociewie": {"pl"},
|
||||
"kscor": {"kw"},
|
||||
"laukika": {"sa"},
|
||||
"leidentr": {"egy"},
|
||||
"lemosin": {"oc"},
|
||||
"lengadoc": {"oc"},
|
||||
"lipaw": {"sl-rozaj"},
|
||||
"ltg1929": {"ltg"},
|
||||
"ltg2007": {"ltg"},
|
||||
"luna1918": {"ru"},
|
||||
"lycopol": {"cop"},
|
||||
"mdcegyp": {"egy"},
|
||||
"mdctrans": {"egy"},
|
||||
"mesokem": {"cop"},
|
||||
"metelko": {"sl"},
|
||||
"monoton": {"el"},
|
||||
"ndyuka": {"djk"},
|
||||
"nedis": {"sl"},
|
||||
"newfound": {"en-CA"},
|
||||
"nicard": {"oc"},
|
||||
"njiva": {"sl-rozaj"},
|
||||
"nulik": {"vo"},
|
||||
"osojs": {"sl-rozaj"},
|
||||
"oxendict": {"en"},
|
||||
"pahawh2": {"mww", "hnj"},
|
||||
"pahawh3": {"mww", "hnj"},
|
||||
"pahawh4": {"mww", "hnj"},
|
||||
"pamaka": {"djk"},
|
||||
"peano": {"la"},
|
||||
"pehoeji": {"nan-Latn"},
|
||||
"petr1708": {"ru"},
|
||||
"pinyin": {"zh-Latn", "bo-Latn"},
|
||||
"polyton": {"el"},
|
||||
"provenc": {"oc"},
|
||||
"puter": {"rm"},
|
||||
"rigik": {"vo"},
|
||||
"rozaj": {"sl"},
|
||||
"rumgr": {"rm"},
|
||||
"sahidic": {"cop"},
|
||||
"saigon": {"vi"},
|
||||
"scotland": {"en"},
|
||||
"scouse": {"en"},
|
||||
"simple": {},
|
||||
"solba": {"sl-rozaj"},
|
||||
"sotav": {"kea"},
|
||||
"spanglis": {"en", "es"},
|
||||
"surmiran": {"rm"},
|
||||
"sursilv": {"rm"},
|
||||
"sutsilv": {"rm"},
|
||||
"synnejyl": {"da"},
|
||||
"tailo": {"nan-Latn"},
|
||||
"tarask": {"be"},
|
||||
"tongyong": {"zh-Latn"},
|
||||
"tunumiit": {"kl"},
|
||||
"uccor": {"kw"},
|
||||
"ucrcor": {"kw"},
|
||||
"ulster": {"sco"},
|
||||
"unifon": {"en", "hup", "kyh", "tol", "yur"},
|
||||
"vaidika": {"sa"},
|
||||
"valbadia": {"lld"},
|
||||
"valencia": {"ca"},
|
||||
"vallader": {"rm"},
|
||||
"vecdruka": {"lv"},
|
||||
"viennese": {"de"},
|
||||
"vivaraup": {"oc"},
|
||||
"wadegile": {"zh-Latn"},
|
||||
"xsistemo": {"eo"},
|
||||
}
|
||||
|
||||
// Type: extlang and their associated primary language prefixes from the
|
||||
// IANA Language Subtag Registry:
|
||||
// https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
|
||||
var iana_subtag_registry_extlangs = map[string][]string{
|
||||
"aao": {"ar"},
|
||||
"abh": {"ar"},
|
||||
"abv": {"ar"},
|
||||
"acm": {"ar"},
|
||||
"acq": {"ar"},
|
||||
"acw": {"ar"},
|
||||
"acx": {"ar"},
|
||||
"acy": {"ar"},
|
||||
"adf": {"ar"},
|
||||
"ads": {"sgn"},
|
||||
"aeb": {"ar"},
|
||||
"aec": {"ar"},
|
||||
"aed": {"sgn"},
|
||||
"aen": {"sgn"},
|
||||
"afb": {"ar"},
|
||||
"afg": {"sgn"},
|
||||
"ajp": {"ar"},
|
||||
"ajs": {"sgn"},
|
||||
"apc": {"ar"},
|
||||
"apd": {"ar"},
|
||||
"arb": {"ar"},
|
||||
"arq": {"ar"},
|
||||
"ars": {"ar"},
|
||||
"ary": {"ar"},
|
||||
"arz": {"ar"},
|
||||
"ase": {"sgn"},
|
||||
"asf": {"sgn"},
|
||||
"asp": {"sgn"},
|
||||
"asq": {"sgn"},
|
||||
"asw": {"sgn"},
|
||||
"auz": {"ar"},
|
||||
"avl": {"ar"},
|
||||
"ayh": {"ar"},
|
||||
"ayl": {"ar"},
|
||||
"ayn": {"ar"},
|
||||
"ayp": {"ar"},
|
||||
"bbz": {"ar"},
|
||||
"bfi": {"sgn"},
|
||||
"bfk": {"sgn"},
|
||||
"bjn": {"ms"},
|
||||
"bog": {"sgn"},
|
||||
"bqn": {"sgn"},
|
||||
"bqy": {"sgn"},
|
||||
"btj": {"ms"},
|
||||
"bve": {"ms"},
|
||||
"bvl": {"sgn"},
|
||||
"bvu": {"ms"},
|
||||
"bzs": {"sgn"},
|
||||
"cdo": {"zh"},
|
||||
"cds": {"sgn"},
|
||||
"cjy": {"zh"},
|
||||
"cmn": {"zh"},
|
||||
"cnp": {"zh"},
|
||||
"coa": {"ms"},
|
||||
"cpx": {"zh"},
|
||||
"csc": {"sgn"},
|
||||
"csd": {"sgn"},
|
||||
"cse": {"sgn"},
|
||||
"csf": {"sgn"},
|
||||
"csg": {"sgn"},
|
||||
"csl": {"sgn"},
|
||||
"csn": {"sgn"},
|
||||
"csp": {"zh"},
|
||||
"csq": {"sgn"},
|
||||
"csr": {"sgn"},
|
||||
"csx": {"sgn"},
|
||||
"czh": {"zh"},
|
||||
"czo": {"zh"},
|
||||
"doq": {"sgn"},
|
||||
"dse": {"sgn"},
|
||||
"dsl": {"sgn"},
|
||||
"dsz": {"sgn"},
|
||||
"dup": {"ms"},
|
||||
"ecs": {"sgn"},
|
||||
"ehs": {"sgn"},
|
||||
"esl": {"sgn"},
|
||||
"esn": {"sgn"},
|
||||
"eso": {"sgn"},
|
||||
"eth": {"sgn"},
|
||||
"fcs": {"sgn"},
|
||||
"fse": {"sgn"},
|
||||
"fsl": {"sgn"},
|
||||
"fss": {"sgn"},
|
||||
"gan": {"zh"},
|
||||
"gds": {"sgn"},
|
||||
"gom": {"kok"},
|
||||
"gse": {"sgn"},
|
||||
"gsg": {"sgn"},
|
||||
"gsm": {"sgn"},
|
||||
"gss": {"sgn"},
|
||||
"gus": {"sgn"},
|
||||
"hab": {"sgn"},
|
||||
"haf": {"sgn"},
|
||||
"hak": {"zh"},
|
||||
"hds": {"sgn"},
|
||||
"hji": {"ms"},
|
||||
"hks": {"sgn"},
|
||||
"hnm": {"zh"},
|
||||
"hos": {"sgn"},
|
||||
"hps": {"sgn"},
|
||||
"hsh": {"sgn"},
|
||||
"hsl": {"sgn"},
|
||||
"hsn": {"zh"},
|
||||
"icl": {"sgn"},
|
||||
"iks": {"sgn"},
|
||||
"ils": {"sgn"},
|
||||
"inl": {"sgn"},
|
||||
"ins": {"sgn"},
|
||||
"ise": {"sgn"},
|
||||
"isg": {"sgn"},
|
||||
"isr": {"sgn"},
|
||||
"jak": {"ms"},
|
||||
"jax": {"ms"},
|
||||
"jcs": {"sgn"},
|
||||
"jhs": {"sgn"},
|
||||
"jks": {"sgn"},
|
||||
"jls": {"sgn"},
|
||||
"jos": {"sgn"},
|
||||
"jsl": {"sgn"},
|
||||
"jus": {"sgn"},
|
||||
"kgi": {"sgn"},
|
||||
"knn": {"kok"},
|
||||
"kvb": {"ms"},
|
||||
"kvk": {"sgn"},
|
||||
"kvr": {"ms"},
|
||||
"kxd": {"ms"},
|
||||
"lbs": {"sgn"},
|
||||
"lce": {"ms"},
|
||||
"lcf": {"ms"},
|
||||
"lgs": {"sgn"},
|
||||
"liw": {"ms"},
|
||||
"lls": {"sgn"},
|
||||
"lsb": {"sgn"},
|
||||
"lsc": {"sgn"},
|
||||
"lsg": {"sgn"},
|
||||
"lsl": {"sgn"},
|
||||
"lsn": {"sgn"},
|
||||
"lso": {"sgn"},
|
||||
"lsp": {"sgn"},
|
||||
"lst": {"sgn"},
|
||||
"lsv": {"sgn"},
|
||||
"lsw": {"sgn"},
|
||||
"lsy": {"sgn"},
|
||||
"ltg": {"lv"},
|
||||
"luh": {"zh"},
|
||||
"lvs": {"lv"},
|
||||
"lws": {"sgn"},
|
||||
"lzh": {"zh"},
|
||||
"max": {"ms"},
|
||||
"mdl": {"sgn"},
|
||||
"meo": {"ms"},
|
||||
"mfa": {"ms"},
|
||||
"mfb": {"ms"},
|
||||
"mfs": {"sgn"},
|
||||
"min": {"ms"},
|
||||
"mnp": {"zh"},
|
||||
"mqg": {"ms"},
|
||||
"mre": {"sgn"},
|
||||
"msd": {"sgn"},
|
||||
"msi": {"ms"},
|
||||
"msr": {"sgn"},
|
||||
"mui": {"ms"},
|
||||
"mzc": {"sgn"},
|
||||
"mzg": {"sgn"},
|
||||
"mzy": {"sgn"},
|
||||
"nan": {"zh"},
|
||||
"nbs": {"sgn"},
|
||||
"ncs": {"sgn"},
|
||||
"nsi": {"sgn"},
|
||||
"nsl": {"sgn"},
|
||||
"nsp": {"sgn"},
|
||||
"nsr": {"sgn"},
|
||||
"nzs": {"sgn"},
|
||||
"okl": {"sgn"},
|
||||
"orn": {"ms"},
|
||||
"ors": {"ms"},
|
||||
"pel": {"ms"},
|
||||
"pga": {"ar"},
|
||||
"pgz": {"sgn"},
|
||||
"pks": {"sgn"},
|
||||
"prl": {"sgn"},
|
||||
"prz": {"sgn"},
|
||||
"psc": {"sgn"},
|
||||
"psd": {"sgn"},
|
||||
"pse": {"ms"},
|
||||
"psg": {"sgn"},
|
||||
"psl": {"sgn"},
|
||||
"pso": {"sgn"},
|
||||
"psp": {"sgn"},
|
||||
"psr": {"sgn"},
|
||||
"pys": {"sgn"},
|
||||
"rib": {"sgn"},
|
||||
"rms": {"sgn"},
|
||||
"rnb": {"sgn"},
|
||||
"rsi": {"sgn"},
|
||||
"rsl": {"sgn"},
|
||||
"rsm": {"sgn"},
|
||||
"rsn": {"sgn"},
|
||||
"sdl": {"sgn"},
|
||||
"sfb": {"sgn"},
|
||||
"sfs": {"sgn"},
|
||||
"sgg": {"sgn"},
|
||||
"sgx": {"sgn"},
|
||||
"shu": {"ar"},
|
||||
"sjc": {"zh"},
|
||||
"slf": {"sgn"},
|
||||
"sls": {"sgn"},
|
||||
"sqk": {"sgn"},
|
||||
"sqs": {"sgn"},
|
||||
"sqx": {"sgn"},
|
||||
"ssh": {"ar"},
|
||||
"ssp": {"sgn"},
|
||||
"ssr": {"sgn"},
|
||||
"svk": {"sgn"},
|
||||
"swc": {"sw"},
|
||||
"swh": {"sw"},
|
||||
"swl": {"sgn"},
|
||||
"syy": {"sgn"},
|
||||
"szs": {"sgn"},
|
||||
"tmw": {"ms"},
|
||||
"tse": {"sgn"},
|
||||
"tsm": {"sgn"},
|
||||
"tsq": {"sgn"},
|
||||
"tss": {"sgn"},
|
||||
"tsy": {"sgn"},
|
||||
"tza": {"sgn"},
|
||||
"ugn": {"sgn"},
|
||||
"ugy": {"sgn"},
|
||||
"ukl": {"sgn"},
|
||||
"uks": {"sgn"},
|
||||
"urk": {"ms"},
|
||||
"uzn": {"uz"},
|
||||
"uzs": {"uz"},
|
||||
"vgt": {"sgn"},
|
||||
"vkk": {"ms"},
|
||||
"vkt": {"ms"},
|
||||
"vsi": {"sgn"},
|
||||
"vsl": {"sgn"},
|
||||
"vsv": {"sgn"},
|
||||
"wbs": {"sgn"},
|
||||
"wuu": {"zh"},
|
||||
"xki": {"sgn"},
|
||||
"xml": {"sgn"},
|
||||
"xmm": {"ms"},
|
||||
"xms": {"sgn"},
|
||||
"yds": {"sgn"},
|
||||
"ygs": {"sgn"},
|
||||
"yhs": {"sgn"},
|
||||
"ysl": {"sgn"},
|
||||
"ysm": {"sgn"},
|
||||
"yue": {"zh"},
|
||||
"zib": {"sgn"},
|
||||
"zlm": {"ms"},
|
||||
"zmi": {"ms"},
|
||||
"zsl": {"sgn"},
|
||||
"zsm": {"ms"},
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
//go:build !validator_novalidatefn
|
||||
|
||||
package validator
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"fmt"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
func isValidateFn(fl FieldLevel) bool {
|
||||
const defaultParam = `Validate`
|
||||
|
||||
field := fl.Field()
|
||||
validateFn := cmp.Or(fl.Param(), defaultParam)
|
||||
|
||||
ok, err := tryCallValidateFn(field, validateFn)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
return ok
|
||||
}
|
||||
|
||||
func tryCallValidateFn(field reflect.Value, validateFn string) (bool, error) {
|
||||
method := field.MethodByName(validateFn)
|
||||
if field.CanAddr() && !method.IsValid() {
|
||||
method = field.Addr().MethodByName(validateFn)
|
||||
}
|
||||
|
||||
if !method.IsValid() {
|
||||
return false, fmt.Errorf("unable to call %q on type %q: %w",
|
||||
validateFn, field.Type().String(), errMethodNotFound)
|
||||
}
|
||||
|
||||
returnValues := method.Call([]reflect.Value{})
|
||||
if len(returnValues) == 0 {
|
||||
return false, fmt.Errorf("unable to use result of method %q on type %q: %w",
|
||||
validateFn, field.Type().String(), errMethodReturnNoValues)
|
||||
}
|
||||
|
||||
firstReturnValue := returnValues[0]
|
||||
|
||||
switch firstReturnValue.Kind() {
|
||||
case reflect.Bool:
|
||||
return firstReturnValue.Bool(), nil
|
||||
case reflect.Interface:
|
||||
errorType := reflect.TypeOf((*error)(nil)).Elem()
|
||||
|
||||
if firstReturnValue.Type().Implements(errorType) {
|
||||
return firstReturnValue.IsNil(), nil
|
||||
}
|
||||
|
||||
return false, fmt.Errorf("unable to use result of method %q on type %q: %w (got interface %v expect error)",
|
||||
validateFn, field.Type().String(), errMethodReturnInvalidType, firstReturnValue.Type().String())
|
||||
default:
|
||||
return false, fmt.Errorf("unable to use result of method %q on type %q: %w (got %v expect error or bool)",
|
||||
validateFn, field.Type().String(), errMethodReturnInvalidType, firstReturnValue.Type().String())
|
||||
}
|
||||
}
|
||||
+14
@@ -24,3 +24,17 @@ func WithPrivateFieldValidation() Option {
|
||||
v.privateFieldValidation = true
|
||||
}
|
||||
}
|
||||
|
||||
// WithTagNameFuncBlankOmit makes a blank return from a RegisterTagNameFunc omit
|
||||
// the field from the error namespace instead of silently falling back to the
|
||||
// struct field name.
|
||||
//
|
||||
// This was made opt-in behaviour to maintain backward compatibility with
|
||||
// existing callers that rely on the fallback for error namespaces.
|
||||
//
|
||||
// It is recommended you enable this as it will be the default behaviour in v11+.
|
||||
func WithTagNameFuncBlankOmit() Option {
|
||||
return func(v *Validate) {
|
||||
v.omitBlankFieldNames = true
|
||||
}
|
||||
}
|
||||
+12
-7
@@ -6,7 +6,7 @@ import (
|
||||
)
|
||||
|
||||
var postCodePatternDict = map[string]string{
|
||||
"GB": `^GIR[ ]?0AA|((AB|AL|B|BA|BB|BD|BH|BL|BN|BR|BS|BT|CA|CB|CF|CH|CM|CO|CR|CT|CV|CW|DA|DD|DE|DG|DH|DL|DN|DT|DY|E|EC|EH|EN|EX|FK|FY|G|GL|GY|GU|HA|HD|HG|HP|HR|HS|HU|HX|IG|IM|IP|IV|JE|KA|KT|KW|KY|L|LA|LD|LE|LL|LN|LS|LU|M|ME|MK|ML|N|NE|NG|NN|NP|NR|NW|OL|OX|PA|PE|PH|PL|PO|PR|RG|RH|RM|S|SA|SE|SG|SK|SL|SM|SN|SO|SP|SR|SS|ST|SW|SY|TA|TD|TF|TN|TQ|TR|TS|TW|UB|W|WA|WC|WD|WF|WN|WR|WS|WV|YO|ZE)(\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}))|BFPO[ ]?\d{1,4}$`,
|
||||
"GB": `^(?:GIR[ ]?0AA|((AB|AL|B|BA|BB|BD|BH|BL|BN|BR|BS|BT|CA|CB|CF|CH|CM|CO|CR|CT|CV|CW|DA|DD|DE|DG|DH|DL|DN|DT|DY|E|EC|EH|EN|EX|FK|FY|G|GL|GY|GU|HA|HD|HG|HP|HR|HS|HU|HX|IG|IM|IP|IV|JE|KA|KT|KW|KY|L|LA|LD|LE|LL|LN|LS|LU|M|ME|MK|ML|N|NE|NG|NN|NP|NR|NW|OL|OX|PA|PE|PH|PL|PO|PR|RG|RH|RM|S|SA|SE|SG|SK|SL|SM|SN|SO|SP|SR|SS|ST|SW|SY|TA|TD|TF|TN|TQ|TR|TS|TW|UB|W|WA|WC|WD|WF|WN|WR|WS|WV|YO|ZE)(\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}))|BFPO[ ]?\d{1,4})$`,
|
||||
"JE": `^JE\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}$`,
|
||||
"GG": `^GY\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}$`,
|
||||
"IM": `^IM\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}$`,
|
||||
@@ -29,12 +29,13 @@ var postCodePatternDict = map[string]string{
|
||||
"PT": `^\d{4}([\-]\d{3})?$`,
|
||||
"FI": `^\d{5}$`,
|
||||
"AX": `^22\d{3}$`,
|
||||
"KR": `^\d{3}[\-]\d{3}$`,
|
||||
"KR": `^\d{5}$`,
|
||||
"CN": `^\d{6}$`,
|
||||
"TW": `^\d{3}(\d{2})?$`,
|
||||
"TW": `^\d{3}(\d{2,3})?$`,
|
||||
"SG": `^\d{6}$`,
|
||||
"DZ": `^\d{5}$`,
|
||||
"AD": `^AD\d{3}$`,
|
||||
"AL": `^\d{4}$`,
|
||||
"AR": `^([A-HJ-NP-Z])?\d{4}([A-Z]{3})?$`,
|
||||
"AM": `^(37)?\d{4}$`,
|
||||
"AZ": `^\d{4}$`,
|
||||
@@ -50,7 +51,8 @@ var postCodePatternDict = map[string]string{
|
||||
"KH": `^\d{5}$`,
|
||||
"CV": `^\d{4}$`,
|
||||
"CL": `^\d{7}$`,
|
||||
"CR": `^\d{4,5}|\d{3}-\d{4}$`,
|
||||
"CO": `^\d{6}$`,
|
||||
"CR": `^\d{5}$`,
|
||||
"HR": `^\d{5}$`,
|
||||
"CY": `^\d{4}$`,
|
||||
"CZ": `^\d{3}[ ]?\d{2}$`,
|
||||
@@ -60,16 +62,18 @@ var postCodePatternDict = map[string]string{
|
||||
"EE": `^\d{5}$`,
|
||||
"FO": `^\d{3}$`,
|
||||
"GE": `^\d{4}$`,
|
||||
"GI": `^GI\d{1,2}[ ]?\d[A-Z]{2}$`,
|
||||
"GR": `^\d{3}[ ]?\d{2}$`,
|
||||
"GL": `^39\d{2}$`,
|
||||
"GT": `^\d{5}$`,
|
||||
"HT": `^\d{4}$`,
|
||||
"HN": `^(?:\d{5})?$`,
|
||||
"HU": `^\d{4}$`,
|
||||
"IE": `^[A-Z]\d[A-Z0-9][ ]?[A-Z0-9]{4}$`,
|
||||
"IS": `^\d{3}$`,
|
||||
"IN": `^\d{6}$`,
|
||||
"ID": `^\d{5}$`,
|
||||
"IL": `^\d{5}$`,
|
||||
"IL": `^\d{5}(\d{2})?$`,
|
||||
"JO": `^\d{5}$`,
|
||||
"KZ": `^\d{6}$`,
|
||||
"KE": `^\d{5}$`,
|
||||
@@ -77,7 +81,7 @@ var postCodePatternDict = map[string]string{
|
||||
"LA": `^\d{5}$`,
|
||||
"LV": `^\d{4}$`,
|
||||
"LB": `^(\d{4}([ ]?\d{4})?)?$`,
|
||||
"LI": `^(948[5-9])|(949[0-7])$`,
|
||||
"LI": `^(?:(948[5-9])|(949[0-7]))$`,
|
||||
"LT": `^\d{5}$`,
|
||||
"LU": `^\d{4}$`,
|
||||
"MK": `^\d{4}$`,
|
||||
@@ -92,7 +96,7 @@ var postCodePatternDict = map[string]string{
|
||||
"NP": `^\d{5}$`,
|
||||
"NZ": `^\d{4}$`,
|
||||
"NI": `^((\d{4}-)?\d{3}-\d{3}(-\d{1})?)?$`,
|
||||
"NG": `^(\d{6})?$`,
|
||||
"NG": `^(\d{6}|[A-Z]{2}[ -]?(0[1-9]|[1-9]\d)[ -]?[A-Z0-9]{3}[ -]?[A-Z]{2}[ -]?(0[1-9]|[1-9]\d))?$`,
|
||||
"OM": `^(PC )?\d{3}$`,
|
||||
"PK": `^\d{5}$`,
|
||||
"PY": `^\d{4}$`,
|
||||
@@ -149,6 +153,7 @@ var postCodePatternDict = map[string]string{
|
||||
"MQ": `^9[78]2\d{2}$`,
|
||||
"NC": `^988\d{2}$`,
|
||||
"NE": `^\d{4}$`,
|
||||
"VG": `^VG\d{4}$`,
|
||||
"VI": `^008(([0-4]\d)|(5[01]))([ \-]\d{4})?$`,
|
||||
"VN": `^[0-9]{1,6}$`,
|
||||
"PF": `^987\d{2}$`,
|
||||
|
||||
+19
-11
@@ -7,7 +7,9 @@ import (
|
||||
|
||||
const (
|
||||
alphaRegexString = "^[a-zA-Z]+$"
|
||||
alphaSpaceRegexString = "^[a-zA-Z ]+$"
|
||||
alphaNumericRegexString = "^[a-zA-Z0-9]+$"
|
||||
alphaNumericSpaceRegexString = "^[a-zA-Z0-9 ]+$"
|
||||
alphaUnicodeRegexString = "^[\\p{L}]+$"
|
||||
alphaUnicodeNumericRegexString = "^[\\p{L}\\p{N}]+$"
|
||||
numericRegexString = "^[-+]?[0-9]+(?:\\.[0-9]+)?$"
|
||||
@@ -18,8 +20,9 @@ const (
|
||||
rgbaRegexString = "^rgba\\(\\s*(?:(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])|(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])%\\s*,\\s*(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])%\\s*,\\s*(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])%)\\s*,\\s*(?:(?:0.[1-9]*)|[01])\\s*\\)$"
|
||||
hslRegexString = "^hsl\\(\\s*(?:0|[1-9]\\d?|[12]\\d\\d|3[0-5]\\d|360)\\s*,\\s*(?:(?:0|[1-9]\\d?|100)%)\\s*,\\s*(?:(?:0|[1-9]\\d?|100)%)\\s*\\)$"
|
||||
hslaRegexString = "^hsla\\(\\s*(?:0|[1-9]\\d?|[12]\\d\\d|3[0-5]\\d|360)\\s*,\\s*(?:(?:0|[1-9]\\d?|100)%)\\s*,\\s*(?:(?:0|[1-9]\\d?|100)%)\\s*,\\s*(?:(?:0.[1-9]*)|[01])\\s*\\)$"
|
||||
cmykRegexString = "^cmyk\\((100|[1-9]?\\d)%\\s*,\\s*(100|[1-9]?\\d)%\\s*,\\s*(100|[1-9]?\\d)%\\s*,\\s*(100|[1-9]?\\d)%\\)$"
|
||||
emailRegexString = "^(?:(?:(?:(?:[a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+(?:\\.([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+)*)|(?:(?:\\x22)(?:(?:(?:(?:\\x20|\\x09)*(?:\\x0d\\x0a))?(?:\\x20|\\x09)+)?(?:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(?:(?:[\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}]))))*(?:(?:(?:\\x20|\\x09)*(?:\\x0d\\x0a))?(\\x20|\\x09)+)?(?:\\x22))))@(?:(?:(?:[a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(?:(?:[a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])(?:[a-zA-Z]|\\d|-|\\.|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*(?:[a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.)+(?:(?:[a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(?:(?:[a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])(?:[a-zA-Z]|\\d|-|\\.|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*(?:[a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.?$"
|
||||
e164RegexString = "^\\+[1-9]?[0-9]{7,14}$"
|
||||
e164RegexString = "^\\+?[1-9]\\d{7,14}$"
|
||||
base32RegexString = "^(?:[A-Z2-7]{8})*(?:[A-Z2-7]{2}={6}|[A-Z2-7]{4}={4}|[A-Z2-7]{5}={3}|[A-Z2-7]{7}=|[A-Z2-7]{8})$"
|
||||
base64RegexString = "^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=|[A-Za-z0-9+\\/]{4})$"
|
||||
base64URLRegexString = "^(?:[A-Za-z0-9-_]{4})*(?:[A-Za-z0-9-_]{2}==|[A-Za-z0-9-_]{3}=|[A-Za-z0-9-_]{4})$"
|
||||
@@ -30,7 +33,7 @@ const (
|
||||
uUID3RegexString = "^[0-9a-f]{8}-[0-9a-f]{4}-3[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$"
|
||||
uUID4RegexString = "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"
|
||||
uUID5RegexString = "^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"
|
||||
uUIDRegexString = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
|
||||
uUIDRegexString = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
|
||||
uUID3RFC4122RegexString = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-3[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
|
||||
uUID4RFC4122RegexString = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"
|
||||
uUID5RFC4122RegexString = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-5[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"
|
||||
@@ -53,12 +56,12 @@ const (
|
||||
latitudeRegexString = "^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?)$"
|
||||
longitudeRegexString = "^[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$"
|
||||
sSNRegexString = `^[0-9]{3}[ -]?(0[1-9]|[1-9][0-9])[ -]?([1-9][0-9]{3}|[0-9][1-9][0-9]{2}|[0-9]{2}[1-9][0-9]|[0-9]{3}[1-9])$`
|
||||
hostnameRegexStringRFC952 = `^[a-zA-Z]([a-zA-Z0-9\-]+[\.]?)*[a-zA-Z0-9]$` // https://tools.ietf.org/html/rfc952
|
||||
hostnameRegexStringRFC1123 = `^([a-zA-Z0-9]{1}[a-zA-Z0-9-]{0,62}){1}(\.[a-zA-Z0-9]{1}[a-zA-Z0-9-]{0,62})*?$` // accepts hostname starting with a digit https://tools.ietf.org/html/rfc1123
|
||||
fqdnRegexStringRFC1123 = `^([a-zA-Z0-9]{1}[a-zA-Z0-9-]{0,62})(\.[a-zA-Z0-9]{1}[a-zA-Z0-9-]{0,62})*?(\.[a-zA-Z]{1}[a-zA-Z0-9]{0,62})\.?$` // same as hostnameRegexStringRFC1123 but must contain a non numerical TLD (possibly ending with '.')
|
||||
btcAddressRegexString = `^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$` // bitcoin address
|
||||
btcAddressUpperRegexStringBech32 = `^BC1[02-9AC-HJ-NP-Z]{7,76}$` // bitcoin bech32 address https://en.bitcoin.it/wiki/Bech32
|
||||
btcAddressLowerRegexStringBech32 = `^bc1[02-9ac-hj-np-z]{7,76}$` // bitcoin bech32 address https://en.bitcoin.it/wiki/Bech32
|
||||
hostnameRegexStringRFC952 = `^[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$` // https://tools.ietf.org/html/rfc952
|
||||
hostnameRegexStringRFC1123 = `^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$` // accepts hostname starting with a digit https://tools.ietf.org/html/rfc1123
|
||||
fqdnRegexStringRFC1123 = `^([a-zA-Z0-9]{1}[a-zA-Z0-9-]{0,62})(\.[a-zA-Z0-9]{1}[a-zA-Z0-9-]{0,62})*?(\.[a-zA-Z]{1}[a-zA-Z0-9-]{0,62})\.?$` // same as hostnameRegexStringRFC1123 but must contain a non numerical TLD (possibly ending with '.')
|
||||
btcAddressRegexString = `^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$` // bitcoin address
|
||||
btcAddressUpperRegexStringBech32 = `^BC1[02-9AC-HJ-NP-Z]{7,76}$` // bitcoin bech32 address https://en.bitcoin.it/wiki/Bech32
|
||||
btcAddressLowerRegexStringBech32 = `^bc1[02-9ac-hj-np-z]{7,76}$` // bitcoin bech32 address https://en.bitcoin.it/wiki/Bech32
|
||||
ethAddressRegexString = `^0x[0-9a-fA-F]{40}$`
|
||||
ethAddressUpperRegexString = `^0x[0-9A-F]{40}$`
|
||||
ethAddressLowerRegexString = `^0x[0-9a-f]{40}$`
|
||||
@@ -67,13 +70,14 @@ const (
|
||||
hTMLRegexString = `<[/]?([a-zA-Z]+).*?>`
|
||||
jWTRegexString = "^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$"
|
||||
splitParamsRegexString = `'[^']*'|\S+`
|
||||
bicRegexString = `^[A-Za-z]{6}[A-Za-z0-9]{2}([A-Za-z0-9]{3})?$`
|
||||
bic2014RegexString = `^[A-Za-z]{6}[A-Za-z0-9]{2}([A-Za-z0-9]{3})?$`
|
||||
bic2022RegexString = `^[A-Z0-9]{4}[A-Z]{2}[A-Z0-9]{2}(?:[A-Z0-9]{3})?$`
|
||||
semverRegexString = `^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$` // numbered capture groups https://semver.org/
|
||||
dnsRegexStringRFC1035Label = "^[a-z]([-a-z0-9]*[a-z0-9])?$"
|
||||
cveRegexString = `^CVE-(1999|2\d{3})-(0[^0]\d{2}|0\d[^0]\d{1}|0\d{2}[^0]|[1-9]{1}\d{3,})$` // CVE Format Id https://cve.mitre.org/cve/identifiers/syntaxchange.html
|
||||
mongodbIdRegexString = "^[a-f\\d]{24}$"
|
||||
mongodbConnStringRegexString = "^mongodb(\\+srv)?:\\/\\/(([a-zA-Z\\d]+):([a-zA-Z\\d$:\\/?#\\[\\]@]+)@)?(([a-z\\d.-]+)(:[\\d]+)?)((,(([a-z\\d.-]+)(:(\\d+))?))*)?(\\/[a-zA-Z-_]{1,64})?(\\?(([a-zA-Z]+)=([a-zA-Z\\d]+))(&(([a-zA-Z\\d]+)=([a-zA-Z\\d]+))?)*)?$"
|
||||
cronRegexString = `(@(annually|yearly|monthly|weekly|daily|hourly|reboot))|(@every (\d+(ns|us|µs|ms|s|m|h))+)|((((\d+,)+\d+|((\*|\d+)(\/|-)\d+)|\d+|\*) ?){5,7})`
|
||||
cronRegexString = `^((@(annually|yearly|monthly|weekly|daily|hourly|reboot))|(@every (\d+(ns|us|µs|ms|s|m|h))+)|(([A-Za-z0-9*?][A-Za-z0-9*?/,#L-]+|[*?0-9])( +([A-Za-z0-9*?][A-Za-z0-9*?/,#L-]+|[*?0-9])){4,6}))$`
|
||||
spicedbIDRegexString = `^(([a-zA-Z0-9/_|\-=+]{1,})|\*)$`
|
||||
spicedbPermissionRegexString = "^([a-z][a-z0-9_]{1,62}[a-z0-9])?$"
|
||||
spicedbTypeRegexString = "^([a-z][a-z0-9_]{1,61}[a-z0-9]/)?[a-z][a-z0-9_]{1,62}[a-z0-9]$"
|
||||
@@ -93,6 +97,8 @@ func lazyRegexCompile(str string) func() *regexp.Regexp {
|
||||
|
||||
var (
|
||||
alphaRegex = lazyRegexCompile(alphaRegexString)
|
||||
alphaSpaceRegex = lazyRegexCompile(alphaSpaceRegexString)
|
||||
alphanNumericSpaceRegex = lazyRegexCompile(alphaNumericSpaceRegexString)
|
||||
alphaNumericRegex = lazyRegexCompile(alphaNumericRegexString)
|
||||
alphaUnicodeRegex = lazyRegexCompile(alphaUnicodeRegexString)
|
||||
alphaUnicodeNumericRegex = lazyRegexCompile(alphaUnicodeNumericRegexString)
|
||||
@@ -104,6 +110,7 @@ var (
|
||||
rgbaRegex = lazyRegexCompile(rgbaRegexString)
|
||||
hslRegex = lazyRegexCompile(hslRegexString)
|
||||
hslaRegex = lazyRegexCompile(hslaRegexString)
|
||||
cmykRegex = lazyRegexCompile(cmykRegexString)
|
||||
e164Regex = lazyRegexCompile(e164RegexString)
|
||||
emailRegex = lazyRegexCompile(emailRegexString)
|
||||
base32Regex = lazyRegexCompile(base32RegexString)
|
||||
@@ -151,7 +158,8 @@ var (
|
||||
hTMLRegex = lazyRegexCompile(hTMLRegexString)
|
||||
jWTRegex = lazyRegexCompile(jWTRegexString)
|
||||
splitParamsRegex = lazyRegexCompile(splitParamsRegexString)
|
||||
bicRegex = lazyRegexCompile(bicRegexString)
|
||||
bic2014Regex = lazyRegexCompile(bic2014RegexString)
|
||||
bic2022Regex = lazyRegexCompile(bic2022RegexString)
|
||||
semverRegex = lazyRegexCompile(semverRegexString)
|
||||
dnsRegexRFC1035Label = lazyRegexCompile(dnsRegexStringRFC1035Label)
|
||||
cveRegex = lazyRegexCompile(cveRegexString)
|
||||
|
||||
+1
-1
@@ -147,7 +147,7 @@ func (v *validate) ReportError(field interface{}, fieldName, structFieldName, ta
|
||||
structNs: v.str2,
|
||||
fieldLen: uint8(len(fieldName)),
|
||||
structfieldLen: uint8(len(structFieldName)),
|
||||
value: fv.Interface(),
|
||||
value: getValue(fv),
|
||||
param: param,
|
||||
kind: kind,
|
||||
typ: fv.Type(),
|
||||
|
||||
+99
-3
@@ -310,7 +310,7 @@ func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (er
|
||||
return
|
||||
}
|
||||
|
||||
if err = ut.Add("max-items", "{0} must contain at maximum {1}", false); err != nil {
|
||||
if err = ut.Add("max-items", "{0} must contain at most {1}", false); err != nil {
|
||||
return
|
||||
}
|
||||
if err = ut.AddCardinal("max-items-item", "{0} item", locales.PluralRuleOne, false); err != nil {
|
||||
@@ -548,7 +548,7 @@ func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (er
|
||||
{
|
||||
tag: "lte",
|
||||
customRegisFunc: func(ut ut.Translator) (err error) {
|
||||
if err = ut.Add("lte-string", "{0} must be at maximum {1} in length", false); err != nil {
|
||||
if err = ut.Add("lte-string", "{0} must be at most {1} in length", false); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -564,7 +564,7 @@ func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (er
|
||||
return
|
||||
}
|
||||
|
||||
if err = ut.Add("lte-items", "{0} must contain at maximum {1}", false); err != nil {
|
||||
if err = ut.Add("lte-items", "{0} must contain at most {1}", false); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1074,6 +1074,26 @@ func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (er
|
||||
translation: "{0} can only contain alphanumeric characters",
|
||||
override: false,
|
||||
},
|
||||
{
|
||||
tag: "alphaspace",
|
||||
translation: "{0} can only contain alphabetic and space characters",
|
||||
override: false,
|
||||
},
|
||||
{
|
||||
tag: "alphanumspace",
|
||||
translation: "{0} can only contain alphanumeric and space characters",
|
||||
override: false,
|
||||
},
|
||||
{
|
||||
tag: "alphaunicode",
|
||||
translation: "{0} can only contain unicode alphabetic characters",
|
||||
override: false,
|
||||
},
|
||||
{
|
||||
tag: "alphanumunicode",
|
||||
translation: "{0} can only contain unicode alphanumeric characters",
|
||||
override: false,
|
||||
},
|
||||
{
|
||||
tag: "numeric",
|
||||
translation: "{0} must be a valid numeric value",
|
||||
@@ -1167,6 +1187,62 @@ func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (er
|
||||
return t
|
||||
},
|
||||
},
|
||||
{
|
||||
tag: "startswith",
|
||||
translation: "{0} must start with '{1}'",
|
||||
override: false,
|
||||
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
|
||||
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
|
||||
if err != nil {
|
||||
log.Printf("warning: error translating FieldError: %#v", fe)
|
||||
return fe.(error).Error()
|
||||
}
|
||||
|
||||
return t
|
||||
},
|
||||
},
|
||||
{
|
||||
tag: "endswith",
|
||||
translation: "{0} must end with '{1}'",
|
||||
override: false,
|
||||
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
|
||||
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
|
||||
if err != nil {
|
||||
log.Printf("warning: error translating FieldError: %#v", fe)
|
||||
return fe.(error).Error()
|
||||
}
|
||||
|
||||
return t
|
||||
},
|
||||
},
|
||||
{
|
||||
tag: "startsnotwith",
|
||||
translation: "{0} must not start with '{1}'",
|
||||
override: false,
|
||||
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
|
||||
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
|
||||
if err != nil {
|
||||
log.Printf("warning: error translating FieldError: %#v", fe)
|
||||
return fe.(error).Error()
|
||||
}
|
||||
|
||||
return t
|
||||
},
|
||||
},
|
||||
{
|
||||
tag: "endsnotwith",
|
||||
translation: "{0} must not end with '{1}'",
|
||||
override: false,
|
||||
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
|
||||
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
|
||||
if err != nil {
|
||||
log.Printf("warning: error translating FieldError: %#v", fe)
|
||||
return fe.(error).Error()
|
||||
}
|
||||
|
||||
return t
|
||||
},
|
||||
},
|
||||
{
|
||||
tag: "excludes",
|
||||
translation: "{0} cannot contain the text '{1}'",
|
||||
@@ -1229,6 +1305,11 @@ func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (er
|
||||
translation: "{0} must be a valid ISSN number",
|
||||
override: false,
|
||||
},
|
||||
{
|
||||
tag: "urn_rfc2141",
|
||||
translation: "{0} must be a valid RFC 2141 URN",
|
||||
override: false,
|
||||
},
|
||||
{
|
||||
tag: "uuid",
|
||||
translation: "{0} must be a valid UUID",
|
||||
@@ -1441,6 +1522,11 @@ func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (er
|
||||
return t
|
||||
},
|
||||
},
|
||||
{
|
||||
tag: "timezone",
|
||||
translation: "{0} must be a valid time zone",
|
||||
override: false,
|
||||
},
|
||||
{
|
||||
tag: "postcode_iso3166_alpha2",
|
||||
translation: "{0} does not match postcode format of {1} country",
|
||||
@@ -1479,11 +1565,21 @@ func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (er
|
||||
translation: "{0} must be a valid image",
|
||||
override: false,
|
||||
},
|
||||
{
|
||||
tag: "mimetype",
|
||||
translation: "{0} must be a valid MIME type",
|
||||
override: false,
|
||||
},
|
||||
{
|
||||
tag: "cve",
|
||||
translation: "{0} must be a valid cve identifier",
|
||||
override: false,
|
||||
},
|
||||
{
|
||||
tag: "bcp47_strict_language_tag",
|
||||
translation: "{0} must be a valid BCP 47 language tag",
|
||||
override: false,
|
||||
},
|
||||
{
|
||||
tag: "validateFn",
|
||||
translation: "{0} must be a valid object",
|
||||
|
||||
+33
-3
@@ -9,6 +9,13 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// Valuer is an interface that allows you to expose a method on a type
|
||||
// (including generic types) that returns a value that is supposed to be validated.
|
||||
type Valuer interface {
|
||||
// ValidatorValue returns the value that is supposed to be validated.
|
||||
ValidatorValue() any
|
||||
}
|
||||
|
||||
// extractTypeInternal gets the actual underlying type of field value.
|
||||
// It will dive into pointers, customTypes and return you the
|
||||
// underlying value and it's kind.
|
||||
@@ -23,6 +30,13 @@ BEGIN:
|
||||
return current, reflect.Ptr, nullable
|
||||
}
|
||||
|
||||
if current.CanInterface() {
|
||||
if v, ok := current.Interface().(Valuer); ok {
|
||||
current = reflect.ValueOf(v.ValidatorValue())
|
||||
goto BEGIN
|
||||
}
|
||||
}
|
||||
|
||||
current = current.Elem()
|
||||
goto BEGIN
|
||||
|
||||
@@ -34,6 +48,13 @@ BEGIN:
|
||||
return current, reflect.Interface, nullable
|
||||
}
|
||||
|
||||
if current.CanInterface() {
|
||||
if v, ok := current.Interface().(Valuer); ok {
|
||||
current = reflect.ValueOf(v.ValidatorValue())
|
||||
goto BEGIN
|
||||
}
|
||||
}
|
||||
|
||||
current = current.Elem()
|
||||
goto BEGIN
|
||||
|
||||
@@ -42,6 +63,13 @@ BEGIN:
|
||||
|
||||
default:
|
||||
|
||||
if current.CanInterface() {
|
||||
if v, ok := current.Interface().(Valuer); ok {
|
||||
current = reflect.ValueOf(v.ValidatorValue())
|
||||
goto BEGIN
|
||||
}
|
||||
}
|
||||
|
||||
if v.v.hasCustomFuncs {
|
||||
if fn, ok := v.v.customFuncs[current.Type()]; ok {
|
||||
current = reflect.ValueOf(fn(current))
|
||||
@@ -214,10 +242,12 @@ BEGIN:
|
||||
}
|
||||
|
||||
// if got here there was more namespace, cannot go any deeper
|
||||
panic("Invalid field namespace")
|
||||
// return found=false instead of panicking to handle cases like ValidateMap
|
||||
// where cross-field validators (required_if, etc.) can't navigate non-struct parents
|
||||
return
|
||||
}
|
||||
|
||||
// asInt returns the parameter as a int64
|
||||
// asInt returns the parameter as an int64
|
||||
// or panics if it can't convert
|
||||
func asInt(param string) int64 {
|
||||
i, err := strconv.ParseInt(param, 0, 64)
|
||||
@@ -296,7 +326,7 @@ func fieldMatchesRegexByStringerValOrString(regexFn func() *regexp.Regexp, fl Fi
|
||||
case reflect.String:
|
||||
return regex.MatchString(fl.Field().String())
|
||||
default:
|
||||
if stringer, ok := fl.Field().Interface().(fmt.Stringer); ok {
|
||||
if stringer, ok := getValue(fl.Field()).(fmt.Stringer); ok {
|
||||
return regex.MatchString(stringer.String())
|
||||
} else {
|
||||
return regex.MatchString(fl.Field().String())
|
||||
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
//go:build validator_novalidatefn
|
||||
|
||||
package validator
|
||||
|
||||
func isValidateFn(fl FieldLevel) bool {
|
||||
panic("validateFn is not supported with 'no-validate-fn' tag")
|
||||
}
|
||||
+34
-8
@@ -116,7 +116,7 @@ func (v *validate) traverseField(ctx context.Context, parent reflect.Value, curr
|
||||
|
||||
if ct.hasTag {
|
||||
if kind == reflect.Invalid {
|
||||
v.str1 = string(append(ns, cf.altName...))
|
||||
v.str1 = appendAltName(ns, cf.altName)
|
||||
if v.v.hasTagNameFunc {
|
||||
v.str2 = string(append(structNs, cf.name...))
|
||||
} else {
|
||||
@@ -138,7 +138,7 @@ func (v *validate) traverseField(ctx context.Context, parent reflect.Value, curr
|
||||
return
|
||||
}
|
||||
|
||||
v.str1 = string(append(ns, cf.altName...))
|
||||
v.str1 = appendAltName(ns, cf.altName)
|
||||
if v.v.hasTagNameFunc {
|
||||
v.str2 = string(append(structNs, cf.name...))
|
||||
} else {
|
||||
@@ -192,7 +192,9 @@ OUTER:
|
||||
// VarWithField - this allows for validating against each field within the struct against a specific value
|
||||
// pretty handy in certain situations
|
||||
if len(cf.name) > 0 {
|
||||
ns = append(append(ns, cf.altName...), '.')
|
||||
if len(cf.altName) > 0 {
|
||||
ns = append(append(ns, cf.altName...), '.')
|
||||
}
|
||||
structNs = append(append(structNs, cf.name...), '.')
|
||||
}
|
||||
v.validateStruct(ctx, parent, current, typ, ns, structNs, ct)
|
||||
@@ -218,7 +220,9 @@ OUTER:
|
||||
// VarWithField - this allows for validating against each field within the struct against a specific value
|
||||
// pretty handy in certain situations
|
||||
if len(cf.name) > 0 {
|
||||
ns = append(append(ns, cf.altName...), '.')
|
||||
if len(cf.altName) > 0 {
|
||||
ns = append(append(ns, cf.altName...), '.')
|
||||
}
|
||||
structNs = append(append(structNs, cf.name...), '.')
|
||||
}
|
||||
|
||||
@@ -266,7 +270,7 @@ OUTER:
|
||||
return
|
||||
}
|
||||
default:
|
||||
if v.fldIsPointer && field.Interface() == nil {
|
||||
if v.fldIsPointer && getValue(field) == nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -318,7 +322,7 @@ OUTER:
|
||||
reusableCF := &cField{}
|
||||
|
||||
for _, key := range current.MapKeys() {
|
||||
pv = fmt.Sprintf("%v", key.Interface())
|
||||
pv = fmt.Sprintf("%v", key)
|
||||
|
||||
v.misc = append(v.misc[0:0], cf.name...)
|
||||
v.misc = append(v.misc, '[')
|
||||
@@ -343,6 +347,18 @@ OUTER:
|
||||
// can be nil when just keys being validated
|
||||
if ct.next != nil {
|
||||
v.traverseField(ctx, parent, current.MapIndex(key), ns, structNs, reusableCF, ct.next)
|
||||
} else {
|
||||
// Struct fallback when map values are structs
|
||||
val := current.MapIndex(key)
|
||||
switch val.Kind() {
|
||||
case reflect.Ptr:
|
||||
if val.Elem().Kind() == reflect.Struct {
|
||||
// Dive into the struct so its own tags run
|
||||
v.traverseField(ctx, parent, val, ns, structNs, reusableCF, nil)
|
||||
}
|
||||
case reflect.Struct:
|
||||
v.traverseField(ctx, parent, val, ns, structNs, reusableCF, nil)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
v.traverseField(ctx, parent, current.MapIndex(key), ns, structNs, reusableCF, ct)
|
||||
@@ -403,7 +419,7 @@ OUTER:
|
||||
|
||||
if ct.isBlockEnd || ct.next == nil {
|
||||
// if we get here, no valid 'or' value and no more tags
|
||||
v.str1 = string(append(ns, cf.altName...))
|
||||
v.str1 = appendAltName(ns, cf.altName)
|
||||
|
||||
if v.v.hasTagNameFunc {
|
||||
v.str2 = string(append(structNs, cf.name...))
|
||||
@@ -462,7 +478,7 @@ OUTER:
|
||||
v.ct = ct
|
||||
|
||||
if !ct.fn(ctx, v) {
|
||||
v.str1 = string(append(ns, cf.altName...))
|
||||
v.str1 = appendAltName(ns, cf.altName)
|
||||
|
||||
if v.v.hasTagNameFunc {
|
||||
v.str2 = string(append(structNs, cf.name...))
|
||||
@@ -493,6 +509,16 @@ OUTER:
|
||||
}
|
||||
}
|
||||
|
||||
func appendAltName(ns []byte, altName string) string {
|
||||
if len(altName) > 0 {
|
||||
return string(append(ns, altName...))
|
||||
}
|
||||
if n := len(ns); n > 0 && ns[n-1] == '.' {
|
||||
return string(ns[:n-1])
|
||||
}
|
||||
return string(ns)
|
||||
}
|
||||
|
||||
func getValue(val reflect.Value) interface{} {
|
||||
if val.CanInterface() {
|
||||
return val.Interface()
|
||||
|
||||
+65
-6
@@ -68,7 +68,7 @@ type FilterFunc func(ns []byte) bool
|
||||
|
||||
// CustomTypeFunc allows for overriding or adding custom field type handler functions
|
||||
// field = field value of the type to return a value to be validated
|
||||
// example Valuer from sql drive see https://golang.org/src/database/sql/driver/types.go?s=1210:1293#L29
|
||||
// example Valuer from sql driver see https://golang.org/src/database/sql/driver/types.go?s=1210:1293#L29
|
||||
type CustomTypeFunc func(field reflect.Value) interface{}
|
||||
|
||||
// TagNameFunc allows for adding of a custom tag name parser
|
||||
@@ -96,6 +96,7 @@ type Validate struct {
|
||||
hasTagNameFunc bool
|
||||
requiredStructEnabled bool
|
||||
privateFieldValidation bool
|
||||
omitBlankFieldNames bool
|
||||
}
|
||||
|
||||
// New returns a new instance of 'validate' with sane defaults.
|
||||
@@ -181,7 +182,7 @@ func (v Validate) ValidateMapCtx(ctx context.Context, data map[string]interface{
|
||||
errs[field] = errors.New("The field: '" + field + "' is not a map to dive")
|
||||
}
|
||||
} else if ruleStr, ok := rule.(string); ok {
|
||||
err := v.VarCtx(ctx, data[field], ruleStr)
|
||||
err := v.VarWithKeyCtx(ctx, field, data[field], ruleStr)
|
||||
if err != nil {
|
||||
errs[field] = err
|
||||
}
|
||||
@@ -428,7 +429,7 @@ func (v *Validate) StructFilteredCtx(ctx context.Context, s interface{}, fn Filt
|
||||
}
|
||||
|
||||
// StructPartial validates the fields passed in only, ignoring all others.
|
||||
// Fields may be provided in a namespaced fashion relative to the struct provided
|
||||
// Fields may be provided in a namespaced fashion relative to the struct provided
|
||||
// eg. NestedStruct.Field or NestedArrayField[0].Struct.Name
|
||||
//
|
||||
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
|
||||
@@ -439,7 +440,7 @@ func (v *Validate) StructPartial(s interface{}, fields ...string) error {
|
||||
|
||||
// StructPartialCtx validates the fields passed in only, ignoring all others and allows passing of contextual
|
||||
// validation information via context.Context
|
||||
// Fields may be provided in a namespaced fashion relative to the struct provided
|
||||
// Fields may be provided in a namespaced fashion relative to the struct provided
|
||||
// eg. NestedStruct.Field or NestedArrayField[0].Struct.Name
|
||||
//
|
||||
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
|
||||
@@ -514,7 +515,7 @@ func (v *Validate) StructPartialCtx(ctx context.Context, s interface{}, fields .
|
||||
}
|
||||
|
||||
// StructExcept validates all fields except the ones passed in.
|
||||
// Fields may be provided in a namespaced fashion relative to the struct provided
|
||||
// Fields may be provided in a namespaced fashion relative to the struct provided
|
||||
// i.e. NestedStruct.Field or NestedArrayField[0].Struct.Name
|
||||
//
|
||||
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
|
||||
@@ -525,7 +526,7 @@ func (v *Validate) StructExcept(s interface{}, fields ...string) error {
|
||||
|
||||
// StructExceptCtx validates all fields except the ones passed in and allows passing of contextual
|
||||
// validation information via context.Context
|
||||
// Fields may be provided in a namespaced fashion relative to the struct provided
|
||||
// Fields may be provided in a namespaced fashion relative to the struct provided
|
||||
// i.e. NestedStruct.Field or NestedArrayField[0].Struct.Name
|
||||
//
|
||||
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
|
||||
@@ -681,6 +682,64 @@ func (v *Validate) VarWithValueCtx(ctx context.Context, field interface{}, other
|
||||
return
|
||||
}
|
||||
|
||||
// VarWithKey validates a single variable with a key to be included in the returned error using tag style validation
|
||||
// eg.
|
||||
// var s string
|
||||
// validate.VarWithKey("email_address", s, "required,email")
|
||||
//
|
||||
// WARNING: a struct can be passed for validation eg. time.Time is a struct or
|
||||
// if you have a custom type and have registered a custom type handler, so must
|
||||
// allow it; however unforeseen validations will occur if trying to validate a
|
||||
// struct that is meant to be passed to 'validate.Struct'
|
||||
//
|
||||
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
|
||||
// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors.
|
||||
// validate Array, Slice and maps fields which may contain more than one error
|
||||
func (v *Validate) VarWithKey(key string, field interface{}, tag string) error {
|
||||
return v.VarWithKeyCtx(context.Background(), key, field, tag)
|
||||
}
|
||||
|
||||
// VarWithKeyCtx validates a single variable with a key to be included in the returned error using tag style validation
|
||||
// and allows passing of contextual validation information via context.Context.
|
||||
// eg.
|
||||
// var s string
|
||||
// validate.VarWithKeyCtx("email_address", s, "required,email")
|
||||
//
|
||||
// WARNING: a struct can be passed for validation eg. time.Time is a struct or
|
||||
// if you have a custom type and have registered a custom type handler, so must
|
||||
// allow it; however unforeseen validations will occur if trying to validate a
|
||||
// struct that is meant to be passed to 'validate.Struct'
|
||||
//
|
||||
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
|
||||
// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors.
|
||||
// validate Array, Slice and maps fields which may contain more than one error
|
||||
func (v *Validate) VarWithKeyCtx(ctx context.Context, key string, field interface{}, tag string) (err error) {
|
||||
if len(tag) == 0 || tag == skipValidationTag {
|
||||
return nil
|
||||
}
|
||||
|
||||
ctag := v.fetchCacheTag(tag)
|
||||
|
||||
cField := &cField{
|
||||
name: key,
|
||||
altName: key,
|
||||
namesEqual: true,
|
||||
}
|
||||
|
||||
val := reflect.ValueOf(field)
|
||||
vd := v.pool.Get().(*validate)
|
||||
vd.top = val
|
||||
vd.isPartial = false
|
||||
vd.traverseField(ctx, val, val, vd.ns[0:0], vd.actualNs[0:0], cField, ctag)
|
||||
|
||||
if len(vd.errs) > 0 {
|
||||
err = vd.errs
|
||||
vd.errs = nil
|
||||
}
|
||||
v.pool.Put(vd)
|
||||
return
|
||||
}
|
||||
|
||||
func (v *Validate) registerValidation(tag string, fn FuncCtx, bakedIn bool, nilCheckable bool) error {
|
||||
if len(tag) == 0 {
|
||||
return errors.New("function Key cannot be empty")
|
||||
|
||||
Reference in new issue
Block a user