MSP-8299 vendor update

This commit is contained in:
ziminis committed 2026-11-27 20:10:32 +07:00
1 parent c8e4a014a0
commit 59d487646c
607 files changed
+48706 -13176

No files matched your search

+3 -2
View File
@@ -2,6 +2,7 @@ package handler
import (
"context"
"slices"
"github.com/txix-open/bgjob"
)
@@ -38,8 +39,8 @@ type Sync struct {
// will be the outermost wrapper.
func NewSync(adapter SyncHandlerAdapter, middlewares ...Middleware) Sync {
s := Sync{}
for i := len(middlewares) - 1; i >= 0; i-- {
adapter = middlewares[i](adapter)
for _, middleware := range slices.Backward(middlewares) {
adapter = middleware(adapter)
}
s.handler = adapter
return s
+17
View File
@@ -34,6 +34,9 @@ const (
defaultEnableLogSampling = false
defaultMaxLogSamplingPerSecond = 1000
defaulLogSamplingPassEvery = 100
defaultLogSplitEnabled = false
defaultLogSplitMaxLineKb = log.DefaultMaxLineKb
)
// BaseBootstrap provides the core initialization context for all application types.
@@ -265,11 +268,25 @@ func appConfig(isDev bool) (*app.Config, error) {
}
}
var split *log.SplitConfig
isSplitEnabled := cfg.Optional().Bool("LOGS.SPLIT.ENABLE", defaultLogSplitEnabled)
if !isDev && isSplitEnabled {
maxLineKb := cfg.Optional().Int("LOGS.SPLIT.MAXLINEKB", defaultLogSplitMaxLineKb)
if maxLineKb <= 0 {
maxLineKb = defaultLogSplitMaxLineKb
}
split = &log.SplitConfig{
Enabled: true,
MaxLineKb: maxLineKb,
}
}
return log.Config{
IsInDevMode: isDev,
OutputPaths: outputPaths,
Sampling: sampling,
InitialLevel: initialLevel,
Split: split,
Hooks: []func(entry zapcore.Entry) error{
logCounter.SampledLogCounter(),
},
+1
View File
@@ -308,6 +308,7 @@ func initClusterClient(
},
EndpointsResolver: endpointsResolver,
MetricsAutodiscovery: metricsServiceDiscovery(localConfig, broadcastHost),
ModuleLeaderMode: localConfig.ModuleLeaderMode,
}
schema := rc.GenerateConfigSchema(remoteConfig)
+10 -2
View File
@@ -11,7 +11,7 @@ import "time"
// - MigrationsDirPath: Path to database migrations directory (optional)
// - RemoteConfigOverride: Override content for remote configuration (optional)
// - LogFile: File-based logging configuration
// - Logs: Log sampling and rate limiting configuration
// - Logs: Log sampling and splitting configuration
// - Observability: Sentry and tracing configuration
// - InfraServerPort: Custom port for infrastructure server (optional, defaults to GrpcInnerAddress.Port + 1)
// - HealthcheckHandlerTimeout: Timeout for health check requests
@@ -41,6 +41,7 @@ type LocalConfig struct {
// - DefaultRemoteConfigPath: Custom path for default remote configuration file (optional)
// - RemoteConfigReceiverTimeout: Timeout for receiving remote configuration updates
// - MetricsAutodiscovery: Configuration for Prometheus metrics auto-discovery
// - ModuleLeaderMode: Module leader election mode announced in MODULE:READY (optional)
type ClusteredLocalConfig struct {
LocalConfig
@@ -48,20 +49,27 @@ type ClusteredLocalConfig struct {
DefaultRemoteConfigPath string
RemoteConfigReceiverTimeout time.Duration
MetricsAutodiscovery MetricsAutodiscovery
ModuleLeaderMode string
}
// Logs configures log sampling and rate limiting.
// Logs configures log sampling and splitting.
//
// Fields:
// - Sampling.Enable: Enable log sampling to prevent log flooding
// - Sampling.MaxPerSecond: Maximum log entries per second when sampling is enabled
// - Sampling.PassEvery: Number of log entries to pass before sampling again
// - Split.Enable: Split JSON log records bigger than the limit into parts (default: false, disabled)
// - Split.MaxLineKb: Size of one part in kilobytes (default: 218)
type Logs struct {
Sampling struct {
Enable bool
MaxPerSecond int
PassEvery int
}
Split struct {
Enable bool
MaxLineKb int
}
}
// LogFile configures file-based logging output.
+1
View File
@@ -348,6 +348,7 @@ func (c *Client) notifyModuleReady(ctx context.Context, cli *clientWrapper, requ
RequiredModules: moduleDependencies,
Address: c.moduleInfo.GrpcOuterAddress,
MetricsAutodiscovery: c.moduleInfo.MetricsAutodiscovery,
ModuleLeaderMode: c.moduleInfo.ModuleLeaderMode,
}
_, err := cli.EmitJsonWithAck(ctx, ModuleReady, declaration)
if err != nil {
+12 -3
View File
@@ -10,12 +10,19 @@ const (
GrpcTransport = "grpc"
HttpTransport = "http"
EmptyTransport = "empty"
ModuleLeaderModeNone = ""
ModuleLeaderModeRequestElection = "REQUEST_ELECTION"
ModuleLeaderModeImLeader = "IM_LEADER"
ModuleLeaderModeImFollower = "IM_FOLLOWER"
)
// AddressConfiguration represents the IP address and port for a service endpoint.
// AddressConfiguration represents the IP address and port for a service endpoint,
// and whether this instance is the module leader.
type AddressConfiguration struct {
IP string `json:"ip"`
Port string `json:"port"`
IP string `json:"ip"`
Port string `json:"port"`
IsModuleLeader bool
}
// ConfigData contains configuration data for a module, including version information
@@ -36,6 +43,7 @@ type ModuleInfo struct {
GrpcOuterAddress AddressConfiguration
EndpointsResolver EndpointsResolver
MetricsAutodiscovery *MetricsAutodiscovery
ModuleLeaderMode string
}
// RoutingConfig represents a list of backend declarations for routing configuration.
@@ -52,6 +60,7 @@ type BackendDeclaration struct {
RequiredModules []ModuleDependency
Address AddressConfiguration
MetricsAutodiscovery *MetricsAutodiscovery
ModuleLeaderMode string
}
// EndpointDescriptor describes an HTTP endpoint, including its path, method, authentication
+3 -2
View File
@@ -7,6 +7,7 @@ package client
import (
"context"
"slices"
"strings"
"sync/atomic"
@@ -96,8 +97,8 @@ func New(initialHosts []string, opts ...Option) (*Client, error) {
cli.grpcCli = grpcCli
roundTripper := cli.do
for i := len(cli.middlewares) - 1; i >= 0; i-- {
roundTripper = cli.middlewares[i](roundTripper)
for _, v := range slices.Backward(cli.middlewares) {
roundTripper = v(roundTripper)
}
cli.roundTripper = roundTripper
+3 -2
View File
@@ -8,6 +8,7 @@ import (
"net"
"net/http"
"net/url"
"slices"
"strings"
"time"
@@ -289,8 +290,8 @@ func defaultTransportDialContext(dialer *net.Dialer) func(context.Context, strin
// nolint:ireturn
func joinMiddlewares(root RoundTripper, mws ...Middleware) RoundTripper {
roundTripper := root
for i := len(mws) - 1; i >= 0; i-- {
roundTripper = mws[i](roundTripper)
for _, mw := range slices.Backward(mws) {
roundTripper = mw(roundTripper)
}
return roundTripper
}
+105 -1
View File
@@ -18,6 +18,7 @@
- `WithDevelopmentMode() Option` – включить логирование в режиме разработки
- `WithFileOutput(fileOutput file.Output) Option` – добавить запись логов в файл
- `WithLevel(level Level) Option` – изменить уровень логирования
- `WithSplit(maxLineKb int) Option` – включить разбиение больших JSON-записей на части
#### `NewFromConfig(config Config) (*Adapter, error)`
@@ -143,4 +144,107 @@ func main() {
}
}
```
```
## Разбиение больших записей на части
Если одна JSON-запись не проходит в лимит лог-коллектора,
её можно писать несколькими обычными записями. Разбиение включается полем `Split` в
`log.Config` или опцией `log.WithSplit(maxLineKb)`, в `bootstrap` — секцией `logs.split`
локального конфига:
```yaml
logs:
split:
enable: true # по умолчанию false
maxLineKb: 218 # размер одной части в килобайтах, 218 × 1024 = 223 232 байта
```
Ключи конфига: `LOGS.SPLIT.ENABLE` (по умолчанию `false`) и `LOGS.SPLIT.MAXLINEKB`
(по умолчанию `218`). Одного `maxLineKb` без `enabled: true` недостаточно. В dev-режиме
разбиение не работает: вывод не JSON.
### Контракт части
Запись, которая не влезает в `maxLineKb × 1024` байт, превращается в несколько **обычных**
лог-записей: у каждой свой `level`, `ts` и исходные имена полей. Ничего не
переименовывается и не заворачивается в `payload`. В корень каждой части добавляются:
* `logPackageId` — UUID v4 (RFC 9562), общий для всех частей одной исходной записи;
* `logPackageIndex` — порядковый номер части, начиная с `1`;
* `logPackageTotal` — общее количество частей.
`requestId`, если он был в записи, попадает в корень **каждой** части. `level`, `ts`, `msg` и
`requestId` одинаковы во всех частях: по ним можно фильтровать в VL, и сообщение не теряется
ни в одной части.
Мелкие поля упаковываются в части жадно в исходном порядке. Поле, которое само не влезает в
часть, остаётся под своим именем, а его значение режется на куски: части идут в порядке
`logPackageIndex`, после сборки значение восстанавливается склейкой.
Пример: `responseBody` не влезает в лимит.
```json
{"level":"debug","ts":"...","msg":"http handler: response","requestId":"3365548a...",
"logPackageId":"9f2c...","logPackageIndex":1,"logPackageTotal":3,
"statusCode":200,"elapsedTimeMs":302}
{"level":"debug","ts":"...","msg":"http handler: response","requestId":"3365548a...",
"logPackageId":"9f2c...","logPackageIndex":2,"logPackageTotal":3,
"responseBody":"{\"added\":[],\"changed\":[],\"removed\":[{\"block\":\"ADDRESS\"..."}
{"level":"debug","ts":"...","msg":"http handler: response","requestId":"3365548a...",
"logPackageId":"9f2c...","logPackageIndex":3,"logPackageTotal":3,
"responseBody":"...\"errorType\":\"Уникальность связки\",...}]}"}
```
### Сборка на приёмнике
```
parts := group by logPackageId, sort by logPackageIndex
if len(parts) != logPackageTotal: пачка битая — отбросить
result := {}
for key in {level, ts, msg, requestId}:
if key in parts[0]:
result[key] = parts[0][key] // одинаковые во всех частях, берём из любой
values := map[string][]any // значения полей по частям, в порядке logPackageIndex
for part in parts:
for key, value in part:
if key in {level, ts, msg, logPackageId, logPackageIndex, logPackageTotal, requestId}:
continue
values[key] = append(values[key], value)
for key, list in values:
if len(list) == 1:
result[key] = list[0] // обычное поле (число, строка, bool)
else:
result[key] = concat(list) // куски строкового поля, склеиваем по порядку
```
Правило простое: поле, которое встречается больше одного раза, — это куски одного значения;
встречается один раз — обычное поле как есть. `requestId` и `msg` повторяются в каждой части,
но значения одни и те же, поэтому берутся из любой части.
### Ограничения
* Разбиваются только строковые поля (`String`, `ByteString`, `Error`, `fmt.Stringer`). Если в лимит не влезает
нестроковое поле (объект, массив, число), разбиение не применяется и запись пишется как есть.
* `Any` разбивается по типу значения: `string`, `[]byte`, `error` и `fmt.Stringer` — как соответствующее строковое поле
(zap резолвит их в конкретный тип при создании поля). Значения `struct`, `map`, `slice` (в том числе `[]string`) кодируются как JSON-объект/массив и не разбиваются:
куски склеиваются конкатенацией, для объектов и массивов восстановление структуры невозможно. Если такой объект не влезает в лимит, запись пишется как есть.
Большое тело (например, JSON-ответ) логируйте строкой — `log.String` или `log.ByteString`.
* Если в лимит не влезает сам `msg`, запись пишется как есть.
* Невалидный UTF-8 в большом поле не режется: ширину экранирования нельзя посчитать точно,
запись пишется как есть.
* Поля с пространствами имён (`zap.Namespace`) не разбиваются: после открытия namespace
последующие поля вложены в него, поэтому запись пишется как есть.
* Поля, добавленные к логгеру через `With` (в том числе в `StdLoggerWithLevel`), попадают в
каждую часть; они учитываются при расчёте бюджета, но не режутся.
* Нарезка идёт по байтам с учётом экранирования и откатом до начала UTF-8-символа, поэтому
кириллица и эмодзи не рвутся, а каждая часть укладывается в `maxLineKb × 1024` байт.
* Сэмплирование принимает решение по исходной записи один раз, поэтому пачка пишется целиком
или не пишется вовсе; хуки вызываются один раз на запись.
* `level`, `ts`, `msg` и `requestId` дублируются в каждой части (~200 байт накладных на часть):
это плата за то, что часть остаётся полноценной лог-записью и по ней можно фильтровать.
* Если запись не удалось разложить, она пишется как есть — сбой разбиения не теряет лог.
+3
View File
@@ -21,6 +21,9 @@ type Config struct {
Hooks []func(entry zapcore.Entry) error
// InitialLevel sets the minimum log level.
InitialLevel Level
// Split enables splitting of oversized JSON log records into several parts.
// It is ignored in development mode because the output is not JSON there.
Split *SplitConfig
}
// SamplingConfig is an alias for zap.SamplingConfig.
+83 -6
View File
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"log"
"time"
"github.com/txix-open/isp-kit/errors"
"go.uber.org/zap"
@@ -35,7 +36,12 @@ func NewFromConfig(config Config) (*Adapter, error) {
cfg.DisableStacktrace = true
cfg.DisableCaller = true
cfg.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
cfg.Sampling = config.Sampling
// Splitting is useless for the development encoder, which is not JSON.
var split *SplitConfig
if config.Split != nil && config.Split.enabled() && !config.IsInDevMode {
split = config.Split
}
if config.DisableDefaultOutput {
cfg.OutputPaths = nil
@@ -48,12 +54,22 @@ func NewFromConfig(config Config) (*Adapter, error) {
level := zap.NewAtomicLevelAt(config.InitialLevel)
cfg.Level = level
var opts []zap.Option
if len(config.Hooks) > 0 {
opts = append(opts, zap.Hooks(config.Hooks...))
var (
logger *zap.Logger
err error
)
if split != nil {
logger, err = newSplitLogger(cfg, *split, config.Sampling, config.Hooks)
} else {
cfg.Sampling = config.Sampling
// Hooks are attached to the logger, so they observe the original record
// once instead of every part.
var opts []zap.Option
if len(config.Hooks) > 0 {
opts = append(opts, zap.Hooks(config.Hooks...))
}
logger, err = cfg.Build(opts...)
}
logger, err := cfg.Build(opts...)
if err != nil {
return nil, errors.WithMessage(err, "build logger")
}
@@ -65,6 +81,67 @@ func NewFromConfig(config Config) (*Adapter, error) {
}, nil
}
// newSplitLogger assembles a logger with the splitting core manually: the core
// writes an encoded line to the sink itself to avoid a second encoding, and
// [zap.Config.Build] does not expose the encoder and the sink. The sampler and
// hooks are attached above the core, so a sampling decision and the hooks are
// applied to the original record once.
func newSplitLogger(
cfg zap.Config,
split SplitConfig,
sampling *SamplingConfig,
hooks []func(entry zapcore.Entry) error,
) (*zap.Logger, error) {
sink, _, err := zap.Open(cfg.OutputPaths...)
if err != nil {
return nil, errors.WithMessage(err, "open log output")
}
errSink, _, err := zap.Open(cfg.ErrorOutputPaths...)
if err != nil {
return nil, errors.WithMessage(err, "open log error output")
}
// zap.Open returns a locked sink, so lines from different goroutines do not
// interleave byte by byte.
encoder := zapcore.NewJSONEncoder(cfg.EncoderConfig)
core := newSplittingCore(encoder, sink, cfg.Level, cfg.EncoderConfig, split)
loggerOpts := []zap.Option{zap.ErrorOutput(errSink)}
if !cfg.DisableCaller {
loggerOpts = append(loggerOpts, zap.AddCaller())
}
if !cfg.DisableStacktrace {
loggerOpts = append(loggerOpts, zap.AddStacktrace(zapcore.ErrorLevel))
}
logger := zap.New(core, loggerOpts...)
if sampling != nil {
logger = logger.WithOptions(samplerOption(sampling))
}
if len(hooks) > 0 {
logger = logger.WithOptions(zap.Hooks(hooks...))
}
return logger, nil
}
// samplerOption returns a zap option that samples records the same way
// [zap.Config] does, but can be attached above the splitting core.
func samplerOption(sampling *SamplingConfig) zap.Option {
return zap.WrapCore(func(core zapcore.Core) zapcore.Core {
samplerOpts := make([]zapcore.SamplerOption, 0, 1)
if sampling.Hook != nil {
samplerOpts = append(samplerOpts, zapcore.SamplerHook(sampling.Hook))
}
return zapcore.NewSamplerWithOptions(
core,
time.Second,
sampling.Initial,
sampling.Thereafter,
samplerOpts...,
)
})
}
// Fatal logs a fatal-level message.
func (a *Adapter) Fatal(ctx context.Context, message any, fields ...Field) {
a.Log(ctx, FatalLevel, message, fields...)
+1 -1
View File
@@ -27,7 +27,7 @@ func LogLevelForError(err error) log.Level {
// It uses LogLevelForError to determine the log level and returns the corresponding Logger method.
func LogLevelFuncForError(err error, logger log.Logger) func(ctx context.Context, message any, fields ...log.Field) {
logLevel := LogLevelForError(err)
switch logLevel {
switch logLevel { //nolint:exhaustive
case log.ErrorLevel:
return logger.Error
case log.WarnLevel:
+11
View File
@@ -34,3 +34,14 @@ func WithLevel(level Level) Option {
a.InitialLevel = level
}
}
// WithSplit enables splitting of oversized JSON log records into parts of at
// most maxLineKb kilobytes each. It is ignored in development mode.
func WithSplit(maxLineKb int) Option {
return func(a *Config) {
a.Split = &SplitConfig{
Enabled: true,
MaxLineKb: maxLineKb,
}
}
}
+886
View File
@@ -0,0 +1,886 @@
package log
import (
"fmt"
"strconv"
"unicode/utf8"
"uuid"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/requestid"
"go.uber.org/zap"
"go.uber.org/zap/buffer"
"go.uber.org/zap/zapcore"
)
// Field names added to the root of every part of a split JSON log record. A
// receiver groups parts by [SplitFieldPackageId], sorts them by
// [SplitFieldPackageIndex] and checks that their number is
// [SplitFieldPackageTotal].
const (
// SplitFieldPackageId is the id shared by all parts of one original record.
SplitFieldPackageId = "logPackageId"
// SplitFieldPackageIndex is the 1-based number of a part in a package.
SplitFieldPackageIndex = "logPackageIndex"
// SplitFieldPackageTotal is the total number of parts in a package.
SplitFieldPackageTotal = "logPackageTotal"
)
const (
// DefaultMaxLineKb is the default limit of a part in kilobytes. It is
// 218 KiB and leaves a margin up to the 256 KB limit of a log collector.
DefaultMaxLineKb = 218
// DefaultMaxLineBytes is [DefaultMaxLineKb] in bytes.
DefaultMaxLineBytes = DefaultMaxLineKb * 1024
// probePartNumber is the maximum part number reserved when the overhead of
// a part is measured. It has 9 digits.
probePartNumber = 999999999
// metaFieldsCapacity is the maximum number of package meta fields of a part.
metaFieldsCapacity = 4
// escapedSpecialWidth is the size of a character escaped with a backslash.
escapedSpecialWidth = 2
// escapedControlWidth is the size of a control character escaped as \u00XX.
escapedControlWidth = 6
// controlByteBoundary is the first printable ASCII byte.
controlByteBoundary = 0x20
// jsonBraces is the number of braces around an encoded field.
jsonBraces = 2
// fieldKeySyntaxWidth is the size of the comma, quotes and colon around a
// field key: ,"key": without the key itself.
fieldKeySyntaxWidth = 4
// fieldValueQuotesWidth is the size of the quotes around a string value.
fieldValueQuotesWidth = 2
// bytesPerKb is the number of bytes in a kilobyte.
bytesPerKb = 1024
// minSplitParts is the minimum number of parts of a split record: a record
// that fits into one part is written as is.
minSplitParts = 2
// utf8ContinuationMask and utf8ContinuationPrefix identify a continuation
// byte of a UTF-8 sequence: 10xxxxxx.
utf8ContinuationMask = 0xC0
utf8ContinuationPrefix = 0x80
// decimalBase is the base of the decimal representation of an integer.
decimalBase = 10
)
// errCannotSplit reports that a record cannot be split without losing data.
// Such a record is written as is, see [splittingCore.Write].
var errCannotSplit = errors.New("cannot split log record")
// SplitConfig configures splitting of oversized JSON log records into parts.
//
// When enabled, a record whose JSON representation is longer than
// [SplitConfig.MaxLineKb] kilobytes is written as several ordinary records.
// Every part keeps the original level, time and field names, and additionally
// carries [SplitFieldPackageId], [SplitFieldPackageIndex] and
// [SplitFieldPackageTotal]. The request id, if it was in the record, and the
// message are written to every part as well.
//
// Fields that fit into a part are packed into it unchanged. A field that does
// not fit keeps its name and its value is cut into pieces: concatenation of the
// pieces in the part order restores the value. Only string fields are cut.
//
// Splitting is ignored in development mode, where the output is not JSON.
type SplitConfig struct {
// Enabled turns splitting on. Splitting is off by default.
Enabled bool
// MaxLineKb is the maximum size of one part in kilobytes. A value less than
// or equal to zero makes splitting inactive.
MaxLineKb int
}
// enabled reports whether the configuration requires splitting.
func (c SplitConfig) enabled() bool {
return c.Enabled && c.MaxLineKb > 0
}
// maxLineBytes returns the byte limit of one part.
func (c SplitConfig) maxLineBytes() int {
return c.MaxLineKb * bytesPerKb
}
// splittingCore writes JSON records to a sink and splits oversized records into
// several records.
//
// The core encodes a record once. A record that fits is written to the sink as
// is, without a second encoding. An oversized record is planned and every part
// is encoded and written separately. Every part carries the same level, time,
// message and logger fields, so the parts can be filtered by them.
//
// The core is assembled manually, see [newSplitLogger]: a regular zap core
// encodes and writes a record itself, so a splitting wrapper would have to
// encode every record twice.
//
// The core is safe for concurrent use: zap encoders encode an entry into a new
// buffer and keep no state between calls.
type splittingCore struct {
encoder zapcore.Encoder
sink zapcore.WriteSyncer
level zapcore.LevelEnabler
// bareEncConfig is the encoder config without the record envelope: it is
// used to measure a single field.
bareEncConfig zapcore.EncoderConfig
maxLineBytes int
// withRequestId reports whether the request id is attached to the logger by
// With. The encoders write it into every record, so a meta request id field
// is not added.
withRequestId bool
// withNamespace reports whether a namespace is attached to the logger by
// With. The meta fields of a part would be nested into that namespace, so
// such records are written as is.
withNamespace bool
}
// newSplittingCore creates a core that writes ready lines to sink.
func newSplittingCore(
encoder zapcore.Encoder,
sink zapcore.WriteSyncer,
level zapcore.LevelEnabler,
encConfig zapcore.EncoderConfig,
cfg SplitConfig,
) *splittingCore {
return &splittingCore{
encoder: encoder,
sink: sink,
level: level,
bareEncConfig: fieldOnlyEncoderConfig(encConfig),
maxLineBytes: cfg.maxLineBytes(),
}
}
// fieldOnlyEncoderConfig returns a copy of cfg without the record envelope: a
// field is measured on its own, so no level, time or message is written.
func fieldOnlyEncoderConfig(cfg zapcore.EncoderConfig) zapcore.EncoderConfig {
cfg.LevelKey = ""
cfg.TimeKey = ""
cfg.MessageKey = ""
cfg.NameKey = ""
cfg.CallerKey = ""
cfg.FunctionKey = ""
cfg.StacktraceKey = ""
return cfg
}
// Enabled reports whether the given level is enabled.
func (c *splittingCore) Enabled(level zapcore.Level) bool {
return c.level.Enabled(level)
}
// With returns a new core with the given fields attached to the encoder. The
// request id and namespaces are tracked: they change how the parts are built.
func (c *splittingCore) With(fields []zapcore.Field) zapcore.Core {
if len(fields) == 0 {
return c
}
encoder := c.encoder.Clone()
for i := range fields {
fields[i].AddTo(encoder)
}
clone := *c
clone.encoder = encoder
clone.withRequestId = c.withRequestId || hasField(fields, requestid.LogKey)
clone.withNamespace = c.withNamespace || hasNamespaceField(fields)
return &clone
}
// Check registers the core itself.
func (c *splittingCore) Check(entry zapcore.Entry, checkedEntry *zapcore.CheckedEntry) *zapcore.CheckedEntry {
if !c.Enabled(entry.Level) {
return checkedEntry
}
return checkedEntry.AddCore(entry, c)
}
// Sync flushes the sink.
func (c *splittingCore) Sync() error {
return c.sink.Sync()
}
// Write encodes a record once and writes it to the sink. An oversized record is
// split into parts: every part is encoded and written separately. A record that
// cannot be split is written as is, so a logging call never loses data because
// of splitting.
func (c *splittingCore) Write(entry zapcore.Entry, fields []zapcore.Field) error {
// Escaping only makes a record longer, so the raw content is a lower bound
// of the encoded record. A record that is already longer than the limit does
// not need to be encoded before splitting.
if c.definitelyOversized(entry, fields) {
return c.writeSplit(entry, fields, nil)
}
line, err := c.encoder.EncodeEntry(entry, fields)
if err != nil {
return err
}
if recordLen(line) <= c.maxLineBytes {
return c.writeBuffer(line)
}
return c.writeSplit(entry, fields, line)
}
// writeSplit plans the parts of an oversized record and writes them. The
// encoded whole record is passed when it is already available: it is written as
// is when the record cannot be split.
func (c *splittingCore) writeSplit(
entry zapcore.Entry,
fields []zapcore.Field,
oversizedLine *buffer.Buffer,
) error {
if c.withNamespace {
return c.writeWhole(entry, fields, oversizedLine)
}
sizes := make([]int, len(fields))
if !c.measureFields(fields, sizes) {
return c.writeWhole(entry, fields, oversizedLine)
}
logPackageId := uuid.New().String()
packable, packableSizes, requestIdField, hasRequestId := c.extractRequestId(fields, sizes)
parts := c.planParts(entry, packable, packableSizes, logPackageId, requestIdField, hasRequestId)
if len(parts) < minSplitParts {
return c.writeWhole(entry, fields, oversizedLine)
}
if oversizedLine != nil {
oversizedLine.Free()
}
return c.writeParts(entry, parts, logPackageId, requestIdField, hasRequestId)
}
// writeParts encodes and writes every part with the same encoder as a whole
// record. It stops at the first error: the remaining parts are not written
// when the encoder or the sink has failed.
func (c *splittingCore) writeParts(
entry zapcore.Entry,
parts [][]zapcore.Field,
logPackageId string,
requestIdField zapcore.Field,
hasRequestId bool,
) error {
for i, part := range parts {
partFields := make([]zapcore.Field, 0, len(part)+metaFieldsCapacity)
partFields = append(partFields,
metaFields(logPackageId, i+1, len(parts), requestIdField, hasRequestId)...)
partFields = append(partFields, part...)
line, err := c.encoder.EncodeEntry(entry, partFields)
if err != nil {
return errors.WithMessage(err, "cannot encode log part")
}
err = c.writeBuffer(line)
if err != nil {
return errors.WithMessage(err, "cannot write log part")
}
}
return nil
}
// writeWhole writes the record as is. The encoded line is reused when it is
// already available.
func (c *splittingCore) writeWhole(
entry zapcore.Entry,
fields []zapcore.Field,
oversizedLine *buffer.Buffer,
) error {
if oversizedLine != nil {
return c.writeBuffer(oversizedLine)
}
line, err := c.encoder.EncodeEntry(entry, fields)
if err != nil {
return err
}
return c.writeBuffer(line)
}
// writeBuffer writes the encoded line to the sink and releases the buffer.
func (c *splittingCore) writeBuffer(line *buffer.Buffer) error {
defer line.Free()
_, err := c.sink.Write(line.Bytes())
return err
}
// definitelyOversized reports whether the raw content of the record is already
// longer than the limit. Every byte takes at least one byte in the JSON output,
// so such a record is definitely oversized.
func (c *splittingCore) definitelyOversized(entry zapcore.Entry, fields []zapcore.Field) bool {
total := len(entry.Message)
if total > c.maxLineBytes {
return true
}
for i := range fields {
field := fields[i]
if field.Type == zapcore.StringType {
total += len(field.Key) + len(field.String)
} else if field.Type == zapcore.ByteStringType {
value, ok := field.Interface.([]byte)
if ok {
total += len(field.Key) + len(value)
}
}
if total > c.maxLineBytes {
return true
}
}
return false
}
// measureFields fills sizes with the exact size of every field in a record. It
// reports false when a field cannot be measured field by field.
func (c *splittingCore) measureFields(fields []zapcore.Field, sizes []int) bool {
sizer := &fieldSizer{encConfig: c.bareEncConfig, limit: c.maxLineBytes}
for i := range fields {
size, err := sizer.size(fields[i])
if err != nil {
return false
}
sizes[i] = size
}
return true
}
// extractRequestId removes the request id from the packable fields: it is
// written to every part by [metaFields]. When the request id was attached to
// the logger by With, the encoders already write it into every part, so no meta
// field is added and the duplicate is removed. sizes stays aligned with the
// returned fields.
func (c *splittingCore) extractRequestId(
fields []zapcore.Field,
sizes []int,
) ([]zapcore.Field, []int, zapcore.Field, bool) {
requestIdField, hasRequestId := findRequestId(fields)
if !hasRequestId {
return fields, sizes, zapcore.Field{}, false
}
packable, packableSizes := withoutField(fields, sizes, requestid.LogKey)
if c.withRequestId {
return packable, packableSizes, zapcore.Field{}, false
}
return packable, packableSizes, requestIdField, true
}
// planParts packs the fields into parts. Small fields are packed greedily in the
// original order, a field that does not fit into a part is cut into pieces and
// goes to its own parts. sizes contains the exact size of every field. Every
// part carries the whole envelope (level, time, message and logger fields), so
// all parts share the same budget. It returns nil when the record cannot be
// split: the limit is smaller than the envelope (for example, an oversized
// message), a field cannot be packed or a field cannot be cut.
func (c *splittingCore) planParts(
entry zapcore.Entry,
fields []zapcore.Field,
sizes []int,
logPackageId string,
requestIdField zapcore.Field,
hasRequestId bool,
) [][]zapcore.Field {
budget, ok := c.partBudget(entry, logPackageId, requestIdField, hasRequestId)
if !ok {
return nil
}
parts := make([][]zapcore.Field, 0, len(fields)+1)
current := make([]zapcore.Field, 0, len(fields))
currentSize := 0
for i, field := range fields {
if field.Type == zapcore.SkipType {
continue // the field writes nothing, it must not create a part
}
size := sizes[i]
if size > budget {
if len(current) > 0 {
parts = append(parts, current)
current, currentSize = nil, 0
}
chunks := c.chunkField(field, size, budget)
if chunks == nil {
return nil
}
parts = append(parts, chunks...)
continue
}
if currentSize+size > budget {
if len(current) > 0 {
parts = append(parts, current)
}
current, currentSize = nil, 0
}
current = append(current, field)
currentSize += size
}
if len(current) > 0 {
parts = append(parts, current)
}
return parts
}
// partBudget returns the free space of a part. It reports false when the limit
// is smaller than the envelope, for example when the message itself does not fit
// into a part.
func (c *splittingCore) partBudget(
entry zapcore.Entry,
logPackageId string,
requestIdField zapcore.Field,
hasRequestId bool,
) (int, bool) {
baseline, err := c.partBaseline(entry, logPackageId, requestIdField, hasRequestId)
if err != nil {
return 0, false
}
budget := c.maxLineBytes - baseline
if budget <= 0 {
return 0, false
}
return budget, true
}
// partBaseline returns the size of a part without user fields: the envelope,
// the fields of the logger and the package meta fields. The meta fields are
// measured with the maximum 9-digit part numbers, so the baseline is an upper
// bound for any real part.
func (c *splittingCore) partBaseline(
entry zapcore.Entry,
logPackageId string,
requestIdField zapcore.Field,
hasRequestId bool,
) (int, error) {
probeFields := metaFields(logPackageId, probePartNumber, probePartNumber, requestIdField, hasRequestId)
line, err := c.encoder.EncodeEntry(entry, probeFields)
if err != nil {
return 0, err
}
defer line.Free()
return recordLen(line), nil
}
// chunkField cuts a string field into pieces that fit into a part. The field
// keeps its name. It returns nil when the field cannot be cut without losing
// data: it is not a string field, it contains invalid UTF-8 or it is encoded
// with additional fields (for example, an error with causes).
func (c *splittingCore) chunkField(field zapcore.Field, fieldSize int, budget int) [][]zapcore.Field {
if !utf8.ValidString(field.Key) {
return nil
}
value, ok := stringValue(field)
if !ok || !utf8.ValidString(value) {
return nil
}
keyOverhead := fieldKeyOverhead(field.Key)
// A string field is encoded as a JSON string by definition. An error and a
// stringer field are encoded as a string only when their size matches the
// key and the escaped value: an error with causes, a verbose message or a
// panicking stringer adds extra fields.
if (field.Type == zapcore.ErrorType || field.Type == zapcore.StringerType) &&
fieldSize != keyOverhead+fieldValueQuotesWidth+escapedWidth(value) {
return nil
}
valueBudget := budget - keyOverhead - fieldValueQuotesWidth
if valueBudget <= 0 {
return nil
}
chunks, ok := chunkByBytes(value, valueBudget)
if !ok {
return nil
}
parts := make([][]zapcore.Field, 0, len(chunks))
for _, chunk := range chunks {
parts = append(parts, []zapcore.Field{zap.String(field.Key, chunk)})
}
return parts
}
// fieldSizer returns the size of a field without encoding it when the type
// allows, and falls back to a measuring encoder otherwise.
type fieldSizer struct {
encConfig zapcore.EncoderConfig
encoder zapcore.Encoder
// limit is the limit of the whole record. A string field longer than limit
// cannot fit into a record and is not measured.
limit int
}
// size returns the size of the field in a record, including the separating
// comma.
func (s *fieldSizer) size(field zapcore.Field) (int, error) {
if size, ok := oversizedStringSize(field, s.limit); ok {
return size, nil
}
if size, ok := cheapFieldSize(field); ok {
return size, nil
}
if s.encoder == nil {
s.encoder = zapcore.NewJSONEncoder(s.encConfig)
}
return fieldSize(s.encoder, field)
}
// fieldSize returns the size of a field in a record, including the separating
// comma, by encoding it on its own. A namespace field has no size of its own:
// it changes the structure of the record and cannot be packed field by field.
func fieldSize(encoder zapcore.Encoder, field zapcore.Field) (int, error) {
if field.Type == zapcore.SkipType {
return 0, nil
}
if field.Type == zapcore.NamespaceType {
return 0, errCannotSplit
}
line, err := encoder.EncodeEntry(zapcore.Entry{}, []zapcore.Field{field})
if err != nil {
return 0, err
}
defer line.Free()
// The encoded field is {"key":value}; the braces are not a part of the
// field, the comma before it is.
size := recordLen(line) - jsonBraces
if size < 0 {
return 0, errCannotSplit
}
return size + 1, nil
}
// oversizedStringSize reports whether a string field alone is longer than the
// whole record limit. The returned size is a placeholder larger than any part
// budget: only the fact that the field does not fit is used.
func oversizedStringSize(field zapcore.Field, limit int) (int, bool) {
if limit <= 0 {
return 0, false
}
if field.Type == zapcore.StringType {
if len(field.String) > limit {
return limit + 1, true
}
return 0, false
}
if field.Type == zapcore.ByteStringType {
value, ok := field.Interface.([]byte)
if ok && len(value) > limit {
return limit + 1, true
}
}
return 0, false
}
// cheapFieldSize returns the exact size of a field without encoding it. It
// supports the types with a known JSON representation: skip, strings, byte
// strings, booleans and integers. Invalid UTF-8 and other types are measured by
// an encoder.
func cheapFieldSize(field zapcore.Field) (int, bool) {
if !utf8.ValidString(field.Key) {
return 0, false
}
keyOverhead := fieldKeyOverhead(field.Key)
if field.Type == zapcore.SkipType {
return 0, true
}
if field.Type == zapcore.StringType {
if !utf8.ValidString(field.String) {
return 0, false
}
return keyOverhead + fieldValueQuotesWidth + escapedWidth(field.String), true
}
if field.Type == zapcore.ByteStringType {
value, ok := field.Interface.([]byte)
if !ok || !utf8.Valid(value) {
return 0, false
}
return keyOverhead + fieldValueQuotesWidth + escapedBytesWidth(value), true
}
if field.Type == zapcore.BoolType {
if field.Integer == 1 {
return keyOverhead + len("true"), true
}
return keyOverhead + len("false"), true
}
if isIntFieldType(field.Type) {
return keyOverhead + intWidth(field.Integer), true
}
if isUintFieldType(field.Type) {
// The unsigned value is stored in the signed integer field as a bit
// pattern, see [zapcore.Field].
return keyOverhead + uintWidth(uint64(field.Integer)), true //nolint:gosec
}
return 0, false
}
// isIntFieldType reports whether the field type encodes a signed integer.
func isIntFieldType(fieldType zapcore.FieldType) bool {
return fieldType == zapcore.Int64Type ||
fieldType == zapcore.Int32Type ||
fieldType == zapcore.Int16Type ||
fieldType == zapcore.Int8Type
}
// isUintFieldType reports whether the field type encodes an unsigned integer.
func isUintFieldType(fieldType zapcore.FieldType) bool {
return fieldType == zapcore.Uint64Type ||
fieldType == zapcore.Uint32Type ||
fieldType == zapcore.Uint16Type ||
fieldType == zapcore.Uint8Type ||
fieldType == zapcore.UintptrType
}
// intWidth returns the number of decimal digits of value with the sign.
func intWidth(value int64) int {
var buff [20]byte
return len(strconv.AppendInt(buff[:0], value, decimalBase))
}
// uintWidth returns the number of decimal digits of value.
func uintWidth(value uint64) int {
var buff [20]byte
return len(strconv.AppendUint(buff[:0], value, decimalBase))
}
// metaFields returns the fields that identify a part in a package. The request
// id goes first and the package fields follow it, so the root of a part carries
// level, time and request id, and then the package metadata.
func metaFields(
logPackageId string,
index int,
total int,
requestIdField zapcore.Field,
hasRequestId bool,
) []zapcore.Field {
fields := make([]zapcore.Field, 0, metaFieldsCapacity)
if hasRequestId {
fields = append(fields, requestIdField)
}
fields = append(fields,
zap.String(SplitFieldPackageId, logPackageId),
zap.Int(SplitFieldPackageIndex, index),
zap.Int(SplitFieldPackageTotal, total),
)
return fields
}
// findRequestId returns the request id from the log fields.
func findRequestId(fields []zapcore.Field) (zapcore.Field, bool) {
for i := range fields {
if fields[i].Key == requestid.LogKey && fields[i].Type == zapcore.StringType {
return fields[i], true
}
}
return zapcore.Field{}, false
}
// hasField reports whether the fields contain a field with the given key.
func hasField(fields []zapcore.Field, key string) bool {
for i := range fields {
if fields[i].Key == key {
return true
}
}
return false
}
// withoutField returns the fields and their sizes without all fields with the
// given key.
func withoutField(fields []zapcore.Field, sizes []int, key string) ([]zapcore.Field, []int) {
index := -1
for i := range fields {
if fields[i].Key == key {
index = i
break
}
}
if index < 0 {
return fields, sizes
}
filteredFields := make([]zapcore.Field, 0, len(fields)-1)
filteredSizes := make([]int, 0, len(sizes)-1)
for i := range fields {
if fields[i].Key == key {
continue
}
filteredFields = append(filteredFields, fields[i])
filteredSizes = append(filteredSizes, sizes[i])
}
return filteredFields, filteredSizes
}
// hasNamespaceField reports whether the fields contain a namespace field.
func hasNamespaceField(fields []zapcore.Field) bool {
for i := range fields {
if fields[i].Type == zapcore.NamespaceType {
return true
}
}
return false
}
// stringValue returns the raw value of a string field: a string field, a byte
// string, an error or a stringer. The value of other fields is encoded as JSON
// and cannot be restored by a simple concatenation.
func stringValue(field zapcore.Field) (value string, ok bool) {
if field.Type == zapcore.StringType {
return field.String, true
}
if field.Type == zapcore.ByteStringType {
bytes, isBytes := field.Interface.([]byte)
if !isBytes {
return "", false
}
return string(bytes), true
}
if field.Type == zapcore.ErrorType {
err, isError := field.Interface.(error)
if !isError || err == nil {
return "", false
}
return errorValue(err)
}
if field.Type == zapcore.StringerType {
stringer, isStringer := field.Interface.(fmt.Stringer)
if !isStringer {
return "", false
}
return stringerValue(stringer)
}
return "", false
}
// errorValue returns the text of an error. The Error method may panic, for
// example when the error is a typed nil pointer; such a field cannot be cut.
func errorValue(err error) (value string, ok bool) {
defer func() {
if recover() != nil {
value, ok = "", false
}
}()
return err.Error(), true
}
// stringerValue returns the text of a stringer. The String method may panic,
// for example when the value is a typed nil pointer; such a field cannot be
// cut.
func stringerValue(stringer fmt.Stringer) (value string, ok bool) {
defer func() {
if recover() != nil {
value, ok = "", false
}
}()
return stringer.String(), true
}
// escapedByteWidth maps a byte of a raw string to the number of bytes it takes
// in the JSON output: 1 for a regular byte, 2 for a character escaped with a
// backslash, 6 for a control character escaped as \u00XX and 1 for every byte of
// a valid multibyte UTF-8 sequence.
var escapedByteWidth = newEscapedByteWidth()
func newEscapedByteWidth() *[256]byte {
widths := new([256]byte)
for i := range widths {
widths[i] = 1
}
for i := range controlByteBoundary {
widths[i] = escapedControlWidth
}
widths['"'] = escapedSpecialWidth
widths['\\'] = escapedSpecialWidth
widths['\n'] = escapedSpecialWidth
widths['\r'] = escapedSpecialWidth
widths['\t'] = escapedSpecialWidth
return widths
}
// escapedWidth returns the number of bytes s takes in the JSON output. s must be
// valid UTF-8.
func escapedWidth(s string) int {
width := 0
for i := range len(s) {
width += int(escapedByteWidth[s[i]])
}
return width
}
// escapedBytesWidth returns the number of bytes s takes in the JSON output. s
// must be valid UTF-8.
func escapedBytesWidth(s []byte) int {
width := 0
for i := range s {
width += int(escapedByteWidth[s[i]])
}
return width
}
// fieldKeyOverhead returns the number of bytes taken by the key of a field and
// its separating comma: ,"key":.
func fieldKeyOverhead(key string) int {
return fieldKeySyntaxWidth + escapedWidth(key)
}
// chunkByBytes splits s into chunks whose JSON-escaped size does not exceed
// budget. It never splits a UTF-8 sequence. It returns false when a chunk
// cannot be built: s is not valid UTF-8 or a single character does not fit the
// budget.
func chunkByBytes(s string, budget int) ([]string, bool) {
if budget <= 0 {
return nil, false
}
if s == "" {
return []string{""}, true
}
if !utf8.ValidString(s) {
return nil, false
}
chunks := make([]string, 0, len(s)/budget+1)
for len(s) > 0 {
used := 0
index := 0
for index < len(s) {
width := int(escapedByteWidth[s[index]])
if used+width > budget {
break
}
used += width
index++
}
// Do not cut a UTF-8 sequence: step back to the beginning of the
// current character.
for index > 0 && index < len(s) && isUTF8Continuation(s[index]) {
index--
}
if index == 0 {
// The first character does not fit the budget.
return nil, false
}
chunks = append(chunks, s[:index])
s = s[index:]
}
return chunks, true
}
// isUTF8Continuation reports whether b is a continuation byte of a UTF-8
// sequence (10xxxxxx).
func isUTF8Continuation(b byte) bool {
return b&utf8ContinuationMask == utf8ContinuationPrefix
}
// recordLen returns the size of the encoded record without the line ending.
func recordLen(line *buffer.Buffer) int {
data := line.Bytes()
size := len(data)
if size > 0 && data[size-1] == '\n' {
size--
}
if size > 0 && data[size-1] == '\r' {
size--
}
return size
}
-5
View File
@@ -8,14 +8,9 @@
Проверяет, что удалённая конфигурация соответствует сгенерированной JSON-схеме и проходит валидацию.
* Проверяет отсутствие устаревшего тега `valid`
* Проверяет соответствие структуры JSON-схеме
* Выполняет валидацию значений с помощью `validator.Default`
### `FindTag[T any](v T, tag string) bool`
Рекурсивно проверяет, содержит ли структура тег с указанным именем.
## Usage
### Example usage in test
-36
View File
@@ -5,7 +5,6 @@ package rct
import (
"os"
"reflect"
"testing"
"github.com/stretchr/testify/require"
@@ -21,7 +20,6 @@ import (
// validator tag validation.
//
// The function checks:
// - No deprecated 'valid' tags are present
// - The default configuration file is valid against the generated schema
// - The configuration can be unmarshaled from the file
// - The configuration passes validation
@@ -30,9 +28,6 @@ import (
func Test[T any](t *testing.T, defaultRemoteConfigPath string, remoteConfig T) {
require := require.New(t)
validatorTag := "valid"
require.Falsef(FindTag(remoteConfig, validatorTag), "'%s' tag is not longer supported, you must use https://github.com/go-playground/validator", validatorTag)
defaultRemoteConfig, err := os.ReadFile(defaultRemoteConfigPath)
require.NoError(err)
@@ -58,34 +53,3 @@ func Test[T any](t *testing.T, defaultRemoteConfigPath string, remoteConfig T) {
err = validator.Default.ValidateToError(remoteConfig)
require.NoError(err)
}
// FindTag recursively searches a type for the specified struct tag.
// It traverses structs, maps, arrays, and slices to find any field
// that has the given tag. Returns true if the tag is found.
func FindTag[T any](v T, tag string) bool {
t := reflect.TypeOf(v)
if t == nil {
return false
}
queue := []reflect.Type{t}
for len(queue) > 0 {
cur := queue[0]
queue = queue[1:]
if cur.Kind() == reflect.Ptr {
cur = cur.Elem()
}
// nolint:exhaustive
switch cur.Kind() {
case reflect.Struct:
for field := range cur.Fields() {
if field.Tag.Get(tag) != "" {
return true
}
queue = append(queue, field.Type)
}
case reflect.Map, reflect.Array, reflect.Slice:
queue = append(queue, cur.Elem())
}
}
return false
}
+3
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
File diff suppressed because it is too large. Load diff
+19 -1
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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")