validator

package module
v0.0.28 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 13 Imported by: 0

README

validator

CI codecov Go Reference Release 日本語

kanna-validator generates a Validate method from the validate tags of a struct, as plain if statements with no reflection, and reports whatever breaks as error codes, keyed by the fields' JSON names.

Part of the kanna family of code generators. Requires Go 1.27, for encoding/json/v2.

Install

go get -tool github.com/go-kanna/validator/cmd/kanna-validator

The generated code calls the small runtime at the root of this module, github.com/go-kanna/validator, which the line above already requires.

Use

Mark a struct //kanna:validate and write its rules as you would for go-playground/validator:

package user

//go:generate go tool kanna-validator

//kanna:validate
type CreateUserRequest struct {
	Name     string   `json:"name"     validate:"required,max=50"`
	Age      int      `json:"age"      validate:"gte=18,lte=130"`
	Role     string   `json:"role"     validate:"required,oneof=admin member guest"`
	Tags     []string `json:"tags"     validate:"max=5,dive,max=20"`
	Address  Address  `json:"address"  validate:"required"`
	Password string   `json:"password" validate:"required,min=12"`
	Confirm  string   `json:"confirm"  validate:"eqfield=Password"`
}

//kanna:validate
type Address struct {
	Zip string `json:"zip" validate:"required,pattern=^\\d{3}-\\d{4}$"`
}

go generate ./... writes validator_gen.go next to it:

// Code generated by kanna-validator. DO NOT EDIT.

func (x CreateUserRequest) Validate() error {
	var errs validator.Errors

	if x.Name == "" {
		errs.Add(validator.Field("name"), validator.Blank())
	} else {
		if utf8.RuneCountInString(x.Name) > 50 {
			errs.Add(validator.Field("name"), validator.TooLong(50))
		}
	}

	if x.Age < 18 {
		errs.Add(validator.Field("age"), validator.GreaterThanOrEqualTo(18))
	}
	// ...

	for i := range x.Tags {
		if utf8.RuneCountInString(x.Tags[i]) > 20 {
			errs.Add(validator.Field("tags").Index(i), validator.TooLong(20))
		}
	}

	if x.Address == (Address{}) {
		errs.Add(validator.Field("address"), validator.Blank())
	} else {
		errs.Nest(validator.Field("address"), x.Address.Validate())
	}
	// ...

	return errs.Err()
}

Every rule is an if you can read and stop at in a debugger, and changing a tag changes the generated code, so a change of rules shows up in review.

With two or more kanna generators, run them with go tool kanna gen, which runs them in the order they need.

A rule that does not exist or does not fit its field stops generation, rather than the first request that meets it:

$ go generate ./...
./request.go:5:2: error: unknown rule "requried" (field Name)
  did you mean "required"?
./request.go:6:2: error: rule "email" cannot apply to int (field Age)
./request.go:7:2: error: rule "max" cannot apply to uint8 (field Level)
  max measures strings, slices, and maps; compare a number with lte
./request.go:8:2: error: invalid pattern: error parsing regexp: missing closing ]: `[0-9` (field Zip)
./request.go:10:2: error: eqfield=Pasword: no such field (field Confirm)
  did you mean "Password"?

A misspelled directive, which would otherwise leave the struct without a Validate and say nothing, draws a warning, and so does one a blank line keeps from the struct, which is then no doc comment of it:

./request.go:3:1: warning: "//kanna:validte" is not recognized as a directive
  did you mean "//kanna:validate"?
./request.go:9:1: warning: //kanna:validate is not attached to a declaration, so nothing reads it
  write it right above what it marks, with no blank line between

Rules

The tags are go-playground/validator's; the codes and params are those of Rails' ActiveModel::Validations.

Tag Applies to Code Params
required anything with a zero value blank
min, max, len strings, in characters too_short, too_long, wrong_length count
min, max, len slices, maps, in elements too_few, too_many, wrong_count count
gt, gte, lt, lte, eq, ne numbers greater_than, greater_than_or_equal_to, less_than, ..., other_than count
oneof=a b 'c d' strings, integers inclusion
eqfield=Field a field of the same type, or a pointer to it confirmation attribute: the other's JSON name
pattern=regexp strings invalid
email, url, uuid strings email, url, uuid, from go-kanna/value
rule=Type, rule=pkg.Type what Type holds the rule's own the rule's own
omitempty anything with a zero value lets the zero value past the rules after it
dive slices, arrays, maps applies the rules after it to each element, or each value of a map

Rails reports the length of a collection by the codes of a string's; the lengths of slices and maps have codes of their own, so that a message can count elements rather than characters. A length in characters counts runes, as go-playground does: é written as an e and a combining accent is 2, and the family emoji 👨‍👩‍👧 is 5. pattern= matches anywhere in the string, as Go's regexp.MatchString and JSON Schema's pattern do: pattern=\d{3} accepts "a123b", so write ^ and $ to match the whole of it.

Where it differs from go-playground:

  • Every rule a field breaks is reported, not just the first. A value that fails required is the exception: it is reported blank alone, since anything else it breaks only says again that it is missing.
  • required means "not the zero value": "", 0, false, nil, or IsZero() for a type that has the method. An empty slice that is not nil is there; bound its length with min=1. A 0 sent cannot be told from a 0 never sent, so where a 0, or a value type whose rule accepts its zero, is a value of its own, take a pointer: required then reports only nil.
  • A nil pointer skips every rule but required: a *string tagged max=20 accepts nil, one tagged required,max=20 does not. eqfield naming a pointer compares what it points to, as for the rules on one, and a nil one equals no value: a *string confirming another is reported when it is set and the other is not.
  • A floating-point NaN breaks every comparison it is held to: gte=0 and lte=100 both report it. The generated code negates the requirement, !(x >= 0), as x < 0 would let NaN through, and ne=0 reports NaN too, which differs from every number.
  • pattern= takes the rest of the tag, commas included, so it comes last; a rule after it, such as ,max=20, is warned about as part of the expression. The tag value is a Go string literal, so a backslash is written \\; a tag that does not unquote stops generation instead of being skipped in silence. So does a validate key that Go does not read: Validate:"required", validate: "required" with a space, or a second validate key in one tag.
  • validate:"-" stops generation: a field without a validate tag is left unchecked already, but for a type with Validate, which is always called.
  • min, max, and len bound a length only. A number is compared with gte, lte, and eq, and min=18 on one stops generation, saying so; each rule then means one thing, as gte on a string stops it too.
  • A time.Duration is compared with a duration as time.ParseDuration reads one, such as gte=1s or oneof=0 500ms, rather than a number of nanoseconds, which stops generation. Its count is the duration as Go prints it, the string "1m30s" for gte=90s, alike in the message and in either encoding/json.
  • omitempty comes first among the rules of its level, as it lets the zero value past those after it. The other rules of a level go in any order, but for dive, which applies those after it to each element, and pattern=, which takes the rest. On a pointer or an interface it stops generation, as it would do nothing: a nil one skips every rule but required already, which go-playground needs omitempty for. With no rule after it at its level, it stops generation too, but where the zero value would skip a Validate of the type, or the elements of an array: omitempty alone on a string, or before dive on a slice or map, whose zero value has no elements, does nothing.
  • omitempty is the other side of required: it lets the zero value past, and nothing else. An empty slice or map that is not nil is no zero value, so omitempty,min=1 reports []string{}, as go-playground does. It is what encoding/json/v2 calls omitzero, not its omitempty, which leaves out an empty value.
  • A tag on a field of a struct without a name, in Meta struct{ ... } or []struct{ ... }, stops generation: only a named type gets a Validate, so nothing would check it. Give the struct a name, marked //kanna:validate. So does a tag on a field named _, which nothing can read; such a field is otherwise left alone, even of a type that validates itself.
  • A bound given twice at one level, such as max=5,max=10, and two bounds no value passes together, such as gte=10,lte=5, gt=1,lte=1, or gte=18,eq=7, stop generation: go-playground checks every one, so the field would fail whatever it held.
  • A rule the type decides alone stops generation: one every value passes, such as min=0, gte=0 on a uint, or lte=255 on a uint8, checks nothing, and one none passes, such as gt=255 on a uint8, fails whatever the field holds. The ends are those of an integer type, with int and uint taken as 64 bits. A float has none, as it holds the infinities, and a time.Duration may be negative, so gte=0s on one is a rule.
  • oneof on an enum of kanna-value lists the values of its constants, of those it exports for an enum of another package, which is all that is loaded of it for certain. A value that is none of them, a typo of one say, stops generation, as the field could never hold it. The enum's Validate is called only on a value oneof accepts, so a value it rejects is reported inclusion once.
  • oneof separates its values with spaces, and a value with spaces is quoted in single quotes, as go-playground reads oneof='light blue' red. A quote that encloses no whole value, as in 'red or it's, stops generation, where go-playground drops it and checks another value than the one written. A value cannot hold a single quote, nor a comma, which separates the rules.
  • url takes an absolute URL with a host name, an address a request can reach. It reports mailto:a@example.com, javascript:alert(1), and file:///etc/passwd, which go-playground accepts as URIs with a scheme, and https://:80, a port above 65535, and a space, as in https://example.com/a b, which go-playground accepts as well. Neither checks the scheme: javascript://example.com/%0Aalert(1) passes both, so check it before writing a URL into a link. The rule is go-kanna/value's, at the version your go.mod requires; v0.0.18 still passes a URL with a port but no host name, a port above 65535, and a space.
  • email checks the syntax of a bare address as Go's net/mail reads one (RFC 5322), not whether its domain could exist: a@b, a@localhost, a@[127.0.0.1], and a@-b.com pass, where go-playground's own pattern rejects them. Whether mail reaches an address is for a mail sent to it to find out. It rejects an address that net/mail would rewrite, such as one with a quoted local part ("a b"@example.com), which go-playground accepts: the value is then always kept as it was written.

rule=Type applies the rule of Type to the field's value, or to each element after dive. Type is a value type of kanna-value, known by the shape kanna-value gives it, whose constructor NewType(T) (Type, error) holds a value to its rule; or an enum of kanna-value, whose constructor NewType(string) (Type, error) accepts only its constants. A rule of your own goes in the struct's validate method (see Nesting and hooks), which can call a function shared between structs. A bare Type is one of the struct's package. pkg.Type names its package as Go reads pkg.Type in code: by the name the struct's file imports it under. Go rejects a named import nothing uses, so a package that only a tag names is imported as _, and goes by its own name. Nothing else is searched: a package the file does not import is an error, with what to import. The generated code records at the field what the constructor returns, with the code and params the rule gave it.

Nesting and hooks

A field whose type has Validate() error, or is to have one (another //kanna:validate struct, a string type marked //kanna:enum, whose Validate kanna-value writes, a type validating itself by hand, an interface), is validated with it, and its errors are nested under the field: address.zip, items[2].sku, or labels.primary for a map, whose key is spelled as encoding/json names it, which a String method has no say in. Slices, arrays, and maps of such types are validated element by element without a dive. A map is walked in the order of its keys, or of their names for keys without an order, such as structs, so that its errors come in one order. A type with Validate through an embedded pointer or interface is validated only when that is not nil, as a nil pointer in a field is skipped. Generation stops when another package does not export what would have to be tested for nil. An embedded struct without a JSON name keeps its errors at the level of the struct embedding it, as encoding/json flattens its fields. One tagged json:"-", which encoding/json leaves out instead, keeps them under its Go name, as any field tagged so does.

A rule no tag can express, such as one spanning two fields, goes in a validate method, which the generated Validate calls after every tag has been checked:

func (x CreateUserRequest) validate(errs *validator.Errors) {
	if x.Role == "admin" && x.Age < 21 {
		errs.Add(validator.Field("age"), validator.Fail("too_young_for_admin"))
	}
}

A path is a validator.Path. validator.Field("address", "zip") makes one through fields by their JSON names, and the methods of Path extend it: Index to an element, Key to a map's value, and Field to the fields below, so items[2].sku is validator.Field("items").Index(2).Field("sku"). Key takes the map's key as it is, as in validator.Field("labels").Key(k), and spells it the way encoding/json names the key. An error concerning the struct as a whole goes under validator.Base, "base", as in Rails. Add given Errors, such as what another Validate returned, moves each of them under the path, as Nest does.

kanna-validator checks, as it generates, the paths the hook puts errors under: the first argument of Add and Nest on the Errors it is given, when it starts with validator.Field of constants, validator.Base, or validator.Path{} and goes on with Index, Key, or Field of constants. A path goes through fields by the names their errors go under, and may end at any of them, or in base. Generation stops at a path that names nothing:

user.go:42:11: error: "aeg" is not a path of CreateUserRequest: CreateUserRequest has no field "aeg"
  did you mean "age"?

Each name given to validator.Field is one field, so validator.Field("address.zip") is a field named address.zip, with a hint to write validator.Field("address", "zip"). What follows a value whose Validate kanna-validator does not write, or an interface, is not checked, as what it reports is up to it; when one is embedded without a JSON name, any name at that level passes. Add(validator.Path{}) stops generation too, as an error on the struct as a whole goes under validator.Base, while Nest(validator.Path{}) keeps what it nests at the level of the struct, as for an embedded struct. A string constant in the place of the path, as in Add("id", …), stops generation, with a hint to write validator.Field("id"), validator.Field("address", "zip") for "address.zip", or validator.Base for "base". A Key call whose key cannot be compared, a slice, map, or func, or an array or struct holding one, stops generation too, as it would panic at run time. A path made of names known only at run time, such as validator.Field(name), or going on from one held in a variable, is not checked.

Errors

Validate returns validator.Errors, or nil. It encodes as Rails encodes errors.details, with the fields in the order they first broke:

{
  "name": [{"error": "blank"}],
  "tags[1]": [{"error": "too_long", "count": 20}],
  "confirm": [{"error": "confirmation", "attribute": "password"}]
}

Each FieldError holds its path both as Field, the key above, and as Segments, which tell a field (validator.FieldSegment) from a map key (validator.KeySegment) and an index (validator.IndexSegment): a key is whatever the request sent, which labels.first_note spells like a field, so a message naming the field can go by the last field of the path rather than by a key. FieldNames lists the names of the field segments alone, as a []string, so a package such as go-kanna/i18n names the field through an interface without importing validator.

A field is keyed by the name its json tag gives it, or by its Go name without one, whatever the transport. Behind a gRPC handler, a use case input without json tags reports TodoID; tag the field json:"id" to report the name the proto declares. A message that protoc-gen-go generates carries json tags with the proto's field names already.

The rejected value is never part of an error: errors end up in logs, and the value may be personal data.

Decoding requests

validator.DecodeJSON decodes a request body, validates it, and reports everything wrong with it in one go:

r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
var req user.CreateUserRequest
if err := validator.DecodeJSON(r.Body, &req); err != nil {
	if errs, ok := errors.AsType[validator.Errors](err); ok {
		writeJSON(w, http.StatusUnprocessableEntity, map[string]any{"errors": errs})
		return
	}
	// A *validator.DecodeError: JSON that cannot be read at all.
	writeJSON(w, http.StatusBadRequest, map[string]any{"error": err})
	return
}

A field whose type rejects its value while decoding (a value type of kanna-value, say) does not stop the decoding: the rejection is reported at the field's path, alongside whatever the tags find in the rest. json.Unmarshal cannot do this; it stops at the first rejection, and does not say which field it came from. DecodeJSON decodes through encoding/json/v2, which matches names case-sensitively and rejects duplicate names.

A name the struct has no field for is skipped, as encoding/json and encoding/json/v2 do by default, so a client may send what the server does not read yet. A misspelled name leaves its field unset, and required on it reports so: {"titl":"x"} is reported title: blank. DecodeJSON reads r to its end with no bound on its size: bound a request body with http.MaxBytesReader before passing it.

What it decodes into has to validate itself, as a struct marked //kanna:validate does, one without a rule included: a struct left unmarked does not compile, rather than pass unchecked.

A request that cannot be read at all, rather than one that breaks a rule, fails with a *validator.DecodeError. It holds the JSON pointer to where reading failed and one of these reasons:

Reason The request
syntax is not JSON, or is cut short
trailing goes on after the JSON value
duplicate_name repeats a name in an object
value holds a value its Go type does not take, such as one out of range
read could not be read, such as when http.MaxBytesReader cuts it off

It encodes as {"pointer":"/age","reason":"value"}, and its message reads validator: cannot decode JSON at "/age": value. Like the errors of the rules, neither holds the value, nor the Go type it was meant for, so either can answer the request as it is. The error of encoding/json/v2 behind it, which holds both, is for errors.As, and so is the *http.MaxBytesError of a body too large, for a handler that answers it with 413.

With kanna-value

kanna-value generates value types that hold a value to its rule wherever it goes: when it is built, decoded, or scanned from a database. The email, url, and uuid tags call the same rules, from its package rule, and report the same codes, so a format checked by a tag and one held in a type read alike in an API response.

//kanna:value
type Email struct{ s string }

func (Email) validate(s string) error { return rule.Email(s) }

//kanna:validate
type SignUp struct {
	Email   Email  `json:"email"   validate:"required"`      // the type holds the format; the tag, that it is there
	Website string `json:"website" validate:"omitempty,url"` // the tag checks the format of a plain string
}

An enum of kanna-value, a string type whose generated UnmarshalText and Validate accept only its constants, needs no oneof listing them again, and reports the same code, inclusion:

//kanna:validate
type ListOrders struct {
	Status *model.OrderStatus `json:"status"` // nil when omitted; "shiped" is reported as inclusion
}

rule= applies the rule of a value type to a plain field, through its constructor. A request built from something other than JSON, such as a gRPC message, can take a *time.Time and check it as model.CompletedAt would:

import (
	"time"

	_ "example.com/app/model"
)

//kanna:validate
type UpdateTask struct {
	CompletedAt *time.Time `json:"completed_at" validate:"rule=model.CompletedAt"` // nil skips it
}
	if x.CompletedAt != nil {
		if _, err := model.NewCompletedAt(*x.CompletedAt); err != nil {
			errs.Add(validator.Field("completed_at"), err)
		}
	}

It checks a plain string against the constants of an enum the same way, as rule=model.OrderStatus.

go-kanna/value is a module of its own: go get github.com/go-kanna/value when you use these tags, or go get -tool github.com/go-kanna/value/cmd/kanna-value for its types. A generated file that needs it while your go.mod does not require it gets a warning rather than a build that fails later:

./validator_gen.go: warning: imports github.com/go-kanna/value/rule, which go.mod does not require; run go mod tidy

Linting

wrapcheck reports return errs.Err() in a hand-written Validate as an unwrapped error from another package. Err hands back what was collected, with nothing underneath to wrap, so add it to the signatures wrapcheck ignores:

linters:
  settings:
    wrapcheck:
      extra-ignore-sigs:
        - validator.Errors).Err(

Flags

kanna-validator [flags] [packages]
Flag Meaning
-tags <list> comma-separated build tags
-check verify the output is up to date instead of writing it, including that no output is left over; KANNA_CHECK=1 does the same
-v list the files written, removed, or left unchanged
-deps print what a run reads and writes as JSON, for the kanna command, and exit
-version print the version

The packages default to the one in the current directory, so //go:generate go tool kanna-validator needs no argument. A run that succeeds prints nothing but its warnings. One of them is about the run itself: when no struct in its packages is marked //kanna:validate, it succeeds, since a //go:generate line left behind does no harm, but says so, since the line was most likely meant to go as well:

$ go generate ./...
warning: no struct is marked //kanna:validate in example.com/app/user

Code may call Validate before the first run has written it. kanna-validator type-checks the packages it loads once more with what it is about to write in place, and writes nothing while their code does not compile with it: a mistake the missing method hid is reported then, such as passing what Validate returns where it does not fit.

A package whose structs have all lost //kanna:validate has its validator_gen.go removed, unless code in the packages the run loads still calls their Validate; a file of that name without the generated-code header is never touched. The go generate that removes it ends with open ...: no such file or directory, from go generate itself, which lists a package's files before it runs the generators; the file is gone as it should be (golang/go#36068).

Example

example decodes sign-up requests the way a handler would (a valid one, one with everything wrong at once, an empty one, one the hook rejects, and malformed JSON) and prints the response each gets. CI regenerates it and fails if the output would change.

Performance

bench validates a request like the one in Use with the generated Validate and with go-playground/validator, both reading the same tags; len=8 stands in for pattern=, which go-playground does not have. go-playground is set up to report what kanna-validator does (a required struct must not be its zero value, and a field goes by its JSON name), and a test fails unless the two find the same fields broken.

Request Validator ns/op B/op allocs/op
valid kanna-validator 19 0 0
valid go-playground/validator v10.30.5 553 432 18
seven fields broken kanna-validator 468 1816 25
seven fields broken go-playground/validator v10.30.5 995 2210 51

The median of 10 runs with Go 1.27.3 on an Apple M5 Pro. The generated Validate checks a valid request about 30 times as fast as go-playground, and a broken one about twice as fast with 18% fewer bytes and 51% fewer allocations. A valid request costs the ifs and allocates nothing; a broken one costs the errors it reports, each built with its code, params, and path.

make bench                       # run it once
make bench BENCHFLAGS=-count=10  # often enough for benchstat

Development

make test       # unit tests
make lint       # golangci-lint
make example    # regenerate the example, then build and run it
make bench      # regenerate the benchmark, then run it

License

MIT

Documentation

Overview

Package validator is the runtime that code generated by kanna-validator calls, and what the code inspecting its result works with.

A generated Validate method checks each field with plain Go and collects what broke into Errors: every broken rule rather than the first, each under the path its JSON names spell. The codes and params follow Rails' ActiveModel::Validations (blank, too_long with a count, ...), and Errors encodes as Rails encodes errors.details.

The generator itself is the command in cmd/kanna-validator.

Index

Constants

This section is empty.

Variables

View Source
var Base = Field("base")

Base is the path of an error that concerns the struct as a whole rather than one of its fields, "base" as in Rails.

Functions

func DecodeJSON

func DecodeJSON(r io.Reader, v interface{ Validate() error }) error

DecodeJSON decodes the JSON value r holds into v, which must be a non-nil pointer, and reports everything wrong with it at once. v has to validate itself, as a struct marked //kanna:validate does, so that a struct left unmarked does not pass unchecked.

A value whose type rejects it with a Coded error, as the value types of kanna-value do, does not stop the decoding: the error is recorded at the value's path and decoding goes on. The rejection may come from any method encoding/json/v2 decodes a type with: UnmarshalJSONFrom, UnmarshalJSON, or UnmarshalText. Then what the Validate method of v finds is added, except at and under the paths decoding rejected. Those values were never set, and checking them would only report the absence of a value that was in fact sent.

The result is the Errors of both, or nil. A request that cannot be read, rather than one that breaks a rule, fails with a *DecodeError instead: JSON that is malformed, holds more than one value, or does not fit the Go types, a rejection that is not Coded or that falls on a map key, and a failure to read r.

Decoding follows encoding/json/v2, which, unlike encoding/json, matches names case-sensitively, rejects duplicate names, and skips unknown names. r is read to its end, so a limit on its size, such as http.MaxBytesReader sets, is the caller's to set.

func SortedKeys added in v0.0.28

func SortedKeys[M ~map[K]V, K comparable, V any](m M) []K

SortedKeys returns the keys of m in the order of their names in a path, as Key spells them. A generated Validate walks a map whose keys have no order of their own, such as structs, in it, so that its errors keep one order.

Types

type Coded

type Coded interface {
	error
	Code() string
	Params() map[string]any
}

Coded is an error that names the rule a value broke.

The code is stable enough to key a translated message or an API response, and the params carry what such a message needs. *rule.Error from github.com/go-kanna/value/rule is Coded too, which is how a rule held in a value type and one checked by a tag end up in the same Errors without either package importing the other.

type DecodeError added in v0.0.28

type DecodeError struct {
	// Pointer is the JSON pointer to where reading failed, such as
	// "/address/zip", or "" for the top-level value.
	Pointer jsontext.Pointer `json:"pointer"`

	Reason DecodeReason `json:"reason"`
	// contains filtered or unexported fields
}

DecodeError is why DecodeJSON could not read a request. It says where and why, but never what was sent or what Go type it was meant for, so that it can answer the request as it is, in its message or encoded as JSON, unlike the error it wraps.

func (*DecodeError) Error added in v0.0.28

func (e *DecodeError) Error() string

Error says why and where, such as `validator: cannot decode JSON at "/address": value`. The pointer is quoted, as the names in it come from the request.

func (*DecodeError) Unwrap added in v0.0.28

func (e *DecodeError) Unwrap() error

Unwrap returns the error behind e, which errors.As can tell apart, such as a *json.SemanticError or an *http.MaxBytesError.

type DecodeReason added in v0.0.28

type DecodeReason string

DecodeReason is what kind of request DecodeJSON could not read.

const (
	// ReasonSyntax is JSON that is malformed or cut short.
	ReasonSyntax DecodeReason = "syntax"
	// ReasonTrailing is anything after the JSON value but white space.
	ReasonTrailing DecodeReason = "trailing"
	// ReasonDuplicateName is a name an object already has.
	ReasonDuplicateName DecodeReason = "duplicate_name"
	// ReasonValue is a JSON value, or a name for a map key, that the Go type
	// does not take: one of the wrong kind, such as a string for a struct, a
	// number out of range, a string that is no time, or one a type rejects
	// without a Coded error.
	ReasonValue DecodeReason = "value"
	// ReasonRead is a failure to read the request, such as one
	// http.MaxBytesReader cuts off.
	ReasonRead DecodeReason = "read"
)

The reasons DecodeJSON could not read a request.

type Error

type Error struct {
	// contains filtered or unexported fields
}

Error is the Coded error the built-in rules report. A validate hook reports its own through Fail and FailWith.

Error is used through a pointer: its params make it incomparable, so comparing two Error values with == would panic, while pointers compare by identity.

func Blank

func Blank() *Error

Blank reports a required value left at its zero value.

func Confirmation

func Confirmation(attribute string) *Error

Confirmation reports a value that does not match the field it confirms, whose JSON name is attribute.

func EqualTo

func EqualTo[N number](count N) *Error

EqualTo reports a number other than count. N is any integer or floating-point type, or one defined on it.

func Fail

func Fail(code string) *Error

Fail returns an Error with code.

func FailWith

func FailWith(code string, params map[string]any) *Error

FailWith is Fail with params for the message. params is copied, so the caller may go on to change it.

func GreaterThan

func GreaterThan[N number](count N) *Error

GreaterThan reports a number that is not greater than count. N is any integer or floating-point type, or one defined on it.

func GreaterThanOrEqualTo

func GreaterThanOrEqualTo[N number](count N) *Error

GreaterThanOrEqualTo reports a number below count. N is any integer or floating-point type, or one defined on it.

func Inclusion

func Inclusion() *Error

Inclusion reports a value outside the allowed set.

func Invalid

func Invalid() *Error

Invalid reports a value in the wrong format.

func LessThan

func LessThan[N number](count N) *Error

LessThan reports a number that is not less than count. N is any integer or floating-point type, or one defined on it.

func LessThanOrEqualTo

func LessThanOrEqualTo[N number](count N) *Error

LessThanOrEqualTo reports a number above count. N is any integer or floating-point type, or one defined on it.

func OtherThan

func OtherThan[N number](count N) *Error

OtherThan reports a number equal to count. N is any integer or floating-point type, or one defined on it.

func TooFew added in v0.0.28

func TooFew(count int) *Error

TooFew reports a slice or a map of fewer than count elements.

func TooLong

func TooLong(count int) *Error

TooLong reports a string of more than count characters.

func TooMany added in v0.0.28

func TooMany(count int) *Error

TooMany reports a slice or a map of more than count elements.

func TooShort

func TooShort(count int) *Error

TooShort reports a string of fewer than count characters.

func WrongCount added in v0.0.28

func WrongCount(count int) *Error

WrongCount reports a slice or a map of other than count elements.

func WrongLength

func WrongLength(count int) *Error

WrongLength reports a string of other than count characters.

func (*Error) Code

func (e *Error) Code() string

Code returns the code naming the broken rule.

func (*Error) Error

func (e *Error) Error() string

Error formats the code and then the params in key order, such as "validator: too_long (count=50)".

func (*Error) Params

func (e *Error) Params() map[string]any

Params returns a copy of the params, or nil when there are none.

type Errors

type Errors []FieldError

Errors collects every rule broken while validating a value, in the order they were found. A generated Validate method returns it through Err.

func (*Errors) Add

func (e *Errors) Add(p Path, err error)

Add records err as broken at p. A nil err is ignored, so that the result of a rule can be passed as it is. Errors, such as what another Validate returns, move under p, as Nest moves them.

func (Errors) Err

func (e Errors) Err() error

Err returns e, or nil when nothing broke. Returning e itself would hand the caller a non-nil error holding nothing.

func (Errors) Error

func (e Errors) Error() string

Error lists every broken rule, such as "validator: name: blank; tags[2]: too_long (count=20)".

func (Errors) MarshalJSON

func (e Errors) MarshalJSON() ([]byte, error)

MarshalJSON is MarshalJSONTo for an encoder that knows only json.Marshaler. encoding/json itself calls MarshalJSONTo.

func (Errors) MarshalJSONTo

func (e Errors) MarshalJSONTo(enc *jsontext.Encoder) error

MarshalJSONTo encodes e as Rails encodes errors.details: an object keyed by field, in the order the fields first broke, each holding a list with the code under "error" and the params beside it, in key order.

{"name":[{"error":"blank"}],"tags[2]":[{"error":"too_long","count":20}]}

A param named "error" would hide the code, so it is left out.

func (*Errors) Nest

func (e *Errors) Nest(p Path, err error)

Nest records what validating the value at p reported. The errors of Errors move under p ("address" and "zip" make "address.zip"), and the zero Path leaves them where they are, as for an embedded struct. Any other error is recorded at p itself, or at Base for the zero Path. A nil err is ignored.

func (Errors) Unwrap

func (e Errors) Unwrap() []error

Unwrap returns each FieldError, so that errors.As finds the rule's error behind any of them.

type FieldError

type FieldError struct {
	// Field is the path to the field, spelled with JSON names, such as
	// "address.zip" or "tags[2]"; or "base".
	Field string

	// Segments are the steps of the path, which tell a field from a map key:
	// "notes.first" may be either.
	Segments []Segment

	// Err is the rule's error. It is usually Coded; one that is not reports the
	// code "invalid", Rails' catch-all.
	Err error
}

FieldError is a broken rule together with the field it broke on.

func (FieldError) Code

func (e FieldError) Code() string

Code returns the code of Err, or "invalid" when Err carries none.

func (FieldError) Error

func (e FieldError) Error() string

Error formats the field followed by the code and params, such as "tags[2]: too_long (count=20)". An error that is not Coded contributes its own text instead.

func (FieldError) FieldNames added in v0.0.28

func (e FieldError) FieldNames() []string

FieldNames returns the names of the field segments of the path, in order, leaving out map keys and indexes: "items[2].notes.first" gives items and notes when first is a key. It returns nil without Segments. It lets a package such as go-kanna/i18n name the field without importing validator.

func (FieldError) Params

func (e FieldError) Params() map[string]any

Params returns the params of Err, or nil when Err carries none.

func (FieldError) Path

func (e FieldError) Path() string

Path returns Field. It is the method go-kanna/i18n renders an error by, together with Code and Params, to name the field in a message.

func (FieldError) Unwrap

func (e FieldError) Unwrap() error

Unwrap returns Err.

type Path added in v0.0.28

type Path struct {
	// contains filtered or unexported fields
}

Path is where in a value an error is: the fields, map keys, and slice indexes leading to it. Field starts one, and its methods go on with it. Its zero value is the value itself.

func Field added in v0.0.28

func Field(name string, names ...string) Path

Field returns the path through the fields named name and then names, each by its JSON name, such as Field("address", "zip") for "address.zip". The methods of Path go on with it.

func (Path) Field added in v0.0.28

func (p Path) Field(name string, names ...string) Path

Field returns the path through the fields named name and then names below p, such as Field("items").Index(2).Field("sku") for "items[2].sku".

func (Path) Index added in v0.0.28

func (p Path) Index(i int) Path

Index returns the path to element i of the slice at p, such as "tags[2]".

func (Path) Key added in v0.0.28

func (p Path) Key(key any) Path

Key returns the path to the value under key in the map at p, such as "labels.primary": a map is a JSON object, so its keys are spelled as the names of an object are, as DecodeJSON reports them. key is a key of the map, of a type a map can have keys of.

func (Path) Segments added in v0.0.28

func (p Path) Segments() []Segment

Segments returns the steps of p, in order.

func (Path) String added in v0.0.28

func (p Path) String() string

String spells p with JSON names, as FieldError.Field does, such as "items[2].sku".

type Segment added in v0.0.28

type Segment struct {
	Kind SegmentKind

	// Name is the field's JSON name, or the key spelled as encoding/json names
	// it in an object, for a FieldSegment and a KeySegment.
	Name string

	// Index is the element's index, for an IndexSegment.
	Index int
}

Segment is one step of a path.

type SegmentKind added in v0.0.28

type SegmentKind int

SegmentKind is what a segment of a path steps into.

const (
	// FieldSegment is a field of a struct.
	FieldSegment SegmentKind = iota + 1
	// KeySegment is the value under a key of a map.
	KeySegment
	// IndexSegment is an element of a slice or an array.
	IndexSegment
)

The kinds of segments.

Directories

Path Synopsis
cmd
kanna-validator command
Command kanna-validator generates Validate methods from the validate tags of structs marked //kanna:validate.
Command kanna-validator generates Validate methods from the validate tags of structs marked //kanna:validate.
internal
gen
Package gen generates Validate methods from the validate tags of structs marked //kanna:validate.
Package gen generates Validate methods from the validate tags of structs marked //kanna:validate.

Jump to

Keyboard shortcuts

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