checker
Zero-dependency input validation and in-place normalization with struct tags, 23 locales, and JSON Schema generation
About checker
This large README is shown as a plain-text preview. Read the full README at the source
<p align="center">
<a href="https://pkg.go.dev/github.com/cinar/checker/v2"><img src="https://img.shields.io/badge/Go_Reference-007D9C?style=for-the-badge&logo=go&logoColor=white" alt="Go Reference" /></a>
<a href="LICENSE"><img src="https://img.shields.io/github/license/cinar/checker?style=for-the-badge" alt="License" /></a>
<a href="https://github.com/cinar/checker/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/cinar/checker/ci.yml?branch=main&style=for-the-badge&logo=github&label=CI" alt="Go CI" /></a>
<a href="https://codecov.io/gh/cinar/checker"><img src="https://img.shields.io/codecov/c/github/cinar/checker?style=for-the-badge&logo=codecov&logoColor=white" alt="Codecov" /></a>
<a href="https://github.com/cinar/checker/stargazers"><img src="https://img.shields.io/github/stars/cinar/checker?style=for-the-badge&logo=github&logoColor=white" alt="GitHub Stars" /></a>
</p>
<h1 align="center">
<img src="logo.svg" alt="Checker logo: a tag with a punched checkmark" width="128" height="128" /><br />
Checker
</h1>
<p align="center">Checker is a lightweight Go library for validating and normalizing user input, driven by struct tags or plain function calls, with zero external dependencies.</p>
<p align="center">
<a href="#quickstart-example">Quickstart</a> ·
<a href="#normalizers-provided">Normalizers</a> ·
<a href="#checkers-provided">Checkers</a> ·
<a href="#json-schema-generation">JSON Schema</a> ·
<a href="#localized-error-messages">Locales</a> ·
<a href="#framework-integration">Frameworks</a>
</p>
- **Zero dependencies** — the core module imports nothing beyond the Go standard library.
- **Struct tags or plain functions** — validate a whole struct declaratively, or call checkers directly for one-off values.
- **Checkers and normalizers together** — trim, then require; lowercase, then validate — mixed in any order, in one pass.
- **Cross-field and conditional rules** — compare fields against each other, or require a field only when another has a given value.
- **23 built-in locales** — opt-in, translated error messages, matching the set go-playground/validator ships.
- **JSON Schema generation** — turn a struct's checker tags into a JSON Schema document, for API docs or frontend validation, without hand-maintaining a second copy of your rules.
- **Framework adapters** — thin, separately-versioned `gin`, `echo`, `nethttp`, and `fiber` modules bind a request and validate it in one call.
- **Trojan Source & Unicode normalization** — the built-in `strip-invisible` normalizer strips zero-width/bidi spoofing characters, and the opt-in `nfkc` module folds compatibility characters (fullwidth digits, ligatures, ...) into their canonical form.
- **Context-aware pipelines** — `Pipeline[T]` reuses the same checkers for domain rules that need a `context.Context` (a DB lookup, a tenant claim) struct tags can't carry.
- **Static analysis** — the separate `checkerlint` module catches unknown checker names, type mismatches, and dangling cross-field targets at build time, not runtime.
- **Code generation** — the separate `checkergen` module turns `checkers` tags into reflection-free Go validation code, ~3x faster with far fewer allocations, for structs on a hot path.
- **Command-line interface** — the separate `checker` binary runs any checker or normalizer from a shell script, CI pipeline, or Git hook, with no Go code and no runtime dependency of its own.
## Table of Contents
- [Why Checker?](#why-checker)
- [Usage](#usage)
- [Quickstart Example](#quickstart-example)
- [Interactive Playgrounds & Examples](#interactive-playgrounds--examples)
- [Validating Structs](#validating-structs)
- [Validating Individual Values](#validating-individual-values)
- [Normalizers and Checkers](#normalizers-and-checkers)
- [Normalizers Provided](#normalizers-provided)
- [Checkers Provided](#checkers-provided)
- [Custom Checkers and Normalizers](#custom-checkers-and-normalizers)
- [Slice and Item Level Checkers](#slice-and-item-level-checkers)
- [Optional Fields with `omitempty`](#optional-fields-with-omitempty)
- [Field-Relative and Conditional Checkers](#field-relative-and-conditional-checkers)
- [Programmatic Pipelines (Context-Aware Validation)](#programmatic-pipelines-context-aware-validation)
- [Context-Aware Struct Tags with `CheckStructWithContext`](#context-aware-struct-tags-with-checkstructwithcontext)
- [Localized Error Messages](#localized-error-messages)
- [Custom Error Messages](#custom-error-messages)
- [Structured Errors](#structured-errors)
- [JSON Schema Generation](#json-schema-generation)
- [Framework Integration](#framework-integration)
- [Unicode Normalization (NFKC)](#unicode-normalization-nfkc)
- [Static Analysis](#static-analysis)
- [Code Generation](#code-generation)
- [Command-Line Interface](#command-line-interface)
- [Performance](#performance)
- [Changelog](#changelog)
- [Contributing to the Project](#contributing-to-the-project)
- [License](#license)
## Why Checker?
Validating user input in Go often requires piecing together separate libraries: one for struct validation, another for string trimming and normalization, and custom code or extra tooling for JSON Schemas.
Checker provides a **single, zero-dependency pipeline** designed around three core pillars:
1. **Zero External Dependencies** — The core module imports nothing beyond the Go standard library. No supply-chain bloat or dependency drift.
2. **Unified Normalization & Validation** — Clean, transform, and validate input in one atomic pass (`trim lower required email`). Input is mutated in-place.
3. **Living JSON Schemas** — Struct tags generate Draft 2020-12 JSON Schema documents for frontend contract sharing and API docs without duplicating rules.
### Feature Comparison
| Feature | Checker (`v2`) | go-playground/validator | ozzo-validation |
| :--- | :---: | :---: | :---: |
| **External Dependencies** | **0 (Standard library only)** | 4+ packages | Standard library only |
| **In-place Normalization** | **Built-in (`trim`, `lower`, etc.)** | Not supported | Not supported |
| **JSON Schema Generation** | **Built-in (`checker.JSONSchema`)** | Requires external tooling | Not supported |
| **Cross-field Validation** | **Built-in (`eq-field`, `required-if`, ...)** | Built-in (`eqfield`, etc.) | Custom rules |
| **Slice / Container Rules** | **Container (`@max-len`) + Items** | Items only | Custom loops |
| **Internationalization** | **23 Locales (Opt-in import)** | 23 Locales (Opt-in, per-language package) | Manual translation |
| **API Error Payloads** | **Built-in (`errs.JSON()`)** | Manual formatting | Manual formatting |
Checker's own test coverage is enforced at 100% in CI (see the badge above); third-party coverage numbers change too often to be worth restating here — check each project's own CI badge for its current figure.
## Usage
To begin using the Checker library, install it with the following command:
```bash
go get github.com/cinar/checker/v2
```
Then, import the library into your source file:
```golang
import (
checker "github.com/cinar/checker/v2"
)
```
### Quickstart Example
Here is a real-world registration request showing in-place normalization, cross-field comparison, slice validation, and structured error responses:
```golang
package main
import (
"fmt"
checker "github.com/cinar/checker/v2"
)
type SignupRequest struct {
// 1. Normalizes in-place (trims spaces, converts to lowercase) and validates:
Email string `json:"email" checkers:"trim lower required email"`
Password string `json:"password" checkers:"required min-len:8"`
ConfirmPassword string `json:"confirm_password" checkers:"required eq-field:Password"`
Roles []string `json:"roles" checkers:"@max-len:3 trim alphanumeric"`
}
func main() {
req := &SignupRequest{
Email: " [email protected] ",
Password: "supersecret123",
ConfirmPassword: "supersecret123",
Roles: []string{" admin ", "editor"},
}
// CheckStruct normalizes fields in-place and validates all rules:
errs, valid := checker.CheckStruct(req)
if !valid {
// Marshals errors directly to JSON for HTTP API responses:
data, _ := errs.JSON()
fmt.Println(string(data))
return
}
// Values are sanitized in-place and ready for database persistence:
fmt.Println(req.Email) // "[email protected]"
fmt.Println(req.Roles) // ["admin", "editor"]
}
```
> 🎮 **[Try this example live on the Go Playground](https://go.dev/play/p/FfkXm5oC9ii)**
### Interactive Playgrounds & Examples
Try Checker immediately in your browser via the official Go Playground:
- 🎮 [**Quickstart & Normalization Playground**](https://go.dev/play/p/5X8ukfSOnZ1) — In-place normalization, validation, and JSON error responses.
- 🎮 [**JSON Schema Generation Playground**](https://go.dev/play/p/MkBT8QVY5-c) — Generate Draft 2020-12 schemas from struct tags.
- 🎮 [**Locales (i18n) Playground**](https://go.dev/play/p/9j9L8nI10MR) — Multilingual error messages in German, Spanish, French, and Japanese.
- 🎮 [**Standard net/http Handler Playground**](https://go.dev/play/p/M5cPYl4eDoJ) — Zero-dependency HTTP request validation.
Explore the [**examples/**](examples/) directory for full standalone project templates, including [Gin](examples/gin/) and [Echo](examples/echo/) integrations.
### Validating Structs
Checker can validate user input stored in a struct by listing the checkers in the struct tags for each field. Here is an example:
```golang
type Person struct {
Name string `checkers:"trim required"`
}
person := &Person{
Name: " Onur Cinar ",
}
errors, valid := checker.CheckStruct(person)
if !valid {
// Handle validation errors
}
```
If a field has no `checkers` tag, `CheckStruct` and `JSONSchema` both fall back to reading a `validate` tag instead — the conventional tag name from `go-playground/validator`. This doesn't give Checker any understanding of `validator`'s own tag syntax (only the tag *name* is a fallback, not its contents), but it means a codebase already tagged `validate:"required"` with Checker-compatible rules picks up validation without renaming every tag. An explicit, empty `checkers:""` tag is respected as "no checks" rather than falling back.
### Validating Individual Values
You can also validate individual user input by calling checker functions directly:
```golang
name := " Onur Cinar "
name, err := checker.Check(name, checker.Trim, checker.Required)
if err != nil {
// Handle validation error
}
```
The checkers and normalizers can also be provided through a config string:
```golang
name := " Onur Cinar "
name, err := checker.CheckWithConfig(name, "trim required")
if err != nil {
// Handle validation error
}
```
For simpler validation, you can call individual checker functions:
```golang
name := "Onur Cinar"
err := checker.IsRequired(name)
if err != nil {
// Handle validation error
}
```
## Normalizers and Checkers
Checkers validate user input, while normalizers transform it into a preferred format. For example, a normalizer can trim spaces from a string or convert it to title case.
Although combining checkers and normalizers into a single library might seem unconventional, using them together can be beneficial. They can be mixed in any order when defining validation steps. For instance, you can use the `trim` normalizer with the `required` checker to first trim the input and then ensure it is provided:
```golang
type Person struct {
Name string `checkers:"trim required"`
}
```
## Normalizers Provided
Normalizers mutate string values in-place and pass them to the next checker in the chain:
| Category | Normalizer | Tag | Description |
| :--- | :--- | :--- | :--- |
| **Whitespace** | [`TrimSpace`](https://pkg.go.dev/github.com/cinar/checker/v2#TrimSpace) | `trim` | Trims whitespace from both sides of the string |
| | [`TrimLeft`](https://pkg.go.dev/github.com/cinar/checker/v2#TrimLeft) | `trim-left` | Trims whitespace from the left side of the string |
| | [`TrimRight`](https://pkg.go.dev/github.com/cinar/checker/v2#TrimRight) | `trim-right` | Trims whitespace from the right side of the string |
| **Case** | [`Lower`](https://pkg.go.dev/github.com/cinar/checker/v2#Lower) | `lower` | Converts the string to lowercase |
| | [`Upper`](https://pkg.go.dev/github.com/cinar/checker/v2#Upper) | `upper` | Converts the string to uppercase |
| | [`Title`](https://pkg.go.dev/github.com/cinar/checker/v2#Title) | `title` | Converts the string to title case |
| **Sanitization** | [`HTMLEscape`](https://pkg.go.dev/github.com/cinar/checker/v2#HTMLEscape) | `html-escape` | Escapes special characters in the string for HTML |
| | [`HTMLUnescape`](https://pkg.go.dev/github.com/cinar/checker/v2#HTMLUnescape) | `html-unescape` | Unescapes special characters in the string for HTML |
| | [`URLEscape`](https://pkg.go.dev/github.com/cinar/checker/v2#URLEscape) | `url-escape` | Escapes special characters in the string for URLs |
| | [`URLUnescape`](https://pkg.go.dev/github.com/cinar/checker/v2#URLUnescape) | `url-unescape` | Unescapes special characters in the string for URLs |
| **Security** | [`StripInvisible`](https://pkg.go.dev/github.com/cinar/checker/v2#StripInvisible) | `strip-invisible` | Removes zero-width and bidirectional control characters (the "Trojan Source" spoofing technique, CVE-2021-42574), which an attacker can use to split a keyword-filtered word invisibly or make displayed text diverge from its logical order |
| **Fallback** | [`Default`](https://pkg.go.dev/github.com/cinar/checker/v2#Default) | `default:<value>` | Replaces the value with `<value>` if it's currently its zero value, otherwise leaves it untouched |
Unlike the other normalizers, `default` isn't string-only: it also works on `bool`, the `int`/`uint`/`float` kinds, and a pointer to any of those (a nil pointer gets a freshly allocated default; a non-nil one is left alone). It's a poor fit alongside `omitempty` on the same field — `omitempty` skips every remaining check exactly when the value is zero, which is exactly the case `default` exists to handle, so combining the two on one field means `default` never runs.
`strip-invisible` removes zero-width space, zero-width non-joiner, zero-width joiner, word joiner, the zero-width no-break space (BOM), and the bidirectional embedding/override/isolate control characters. Some of these have legitimate uses in ordinary text — zero-width joiner in emoji sequences, zero-width non-joiner in Persian and other scripts — so apply it only to fields where an invisible character is never expected, such as a handle, username, or search keyword, not general free-text content.
`strip-invisible` handles invisible spoofing characters without pulling in a dependency. For *visible* lookalikes — fullwidth digits, ligatures, and other compatibility characters a naive keyword filter or uniqueness check would treat as distinct from their canonical form — see the opt-in [`nfkc`](#unicode-normalization-nfkc) module instead.
## Checkers Provided
Checkers validate that a value conforms to expected criteria, returning an error if validation fails.
### Strings & Characters
| Checker | Tag Syntax | Description |
| :--- | :--- | :--- |
| [`IsASCII`](https://pkg.go.dev/github.com/cinar/checker/v2#IsASCII) | `ascii` | Ensures the string contains only ASCII characters |
| [`IsAlphanumeric`](https://pkg.go.dev/github.com/cinar/checker/v2#IsAlphanumeric) | `alphanumeric` | Ensures the string contains only letters and numbers |
| [`IsAlpha`](https://pkg.go.dev/github.com/cinar/checker/v2#IsAlpha) | `alpha` | Ensures the string contains only letters |
| [`IsNumeric`](https://pkg.go.dev/github.com/cinar/checker/v2#IsNumeric) | `numeric` | Ensures the string is a valid numeric string, e.g. `"-3.14"` (unlike `digits`, allows a leading sign and a decimal point) |
| [`IsDigits`](https://pkg.go.dev/github.com/cinar/checker/v2#IsDigits) | `digits` | Ensures the string contains only digits |
| [`IsHex`](https://pkg.go.dev/github.com/cinar/checker/v2#IsHex) | `hex` | Ensures the string contains only hexadecimal digits |
| [`IsHexColor`](https://pkg.go.dev/github.com/cinar/checker/v2#IsHexColor) | `hex-color` | Ensures the string is a valid `#`-prefixed hex color code (3, 4, 6, or 8 digits) |
| [`IsBase64`](https://pkg.go.dev/github.com/cinar/checker/v2#IsBase64) | `base64` | Ensures the string is a valid standard (RFC 4648) base64-encoded string |
| [`IsBase64URL`](https://pkg.go.dev/github.com/cinar/checker/v2#IsBase64URL) | `base64-url` | Ensures the string is a valid base64url-encoded string |
| [`IsSlug`](https://pkg.go.dev/github.com/cinar/checker/v2#IsSlug) | `slug` | Ensures the string is a valid URL slug, e.g. `"hello-world"` |
| [`IsContains`](https://pkg.go.dev/github.com/cinar/checker/v2#IsContains) | `contains:<substr>` | Ensures the string contains the given substring |
| [`IsStartsWith`](https://pkg.go.dev/github.com/cinar/checker/v2#IsStartsWith) | `starts-with:<prefix>` | Ensures the string starts with the given prefix |
| [`IsEndsWith`](https://pkg.go.dev/github.com/cinar/checker/v2#IsEndsWith) | `ends-with:<suffix>` | Ensures the string ends with the given suffix |
| [`MakeRegexpChecker`](https://pkg.go.dev/github.com/cinar/checker/v2#MakeRegexpChecker) | `regexp:<pattern>` | Ensures the string matches the pattern |
### Presence, Sizes & Numeric Bounds
| Checker | Tag Syntax | Description |
| :--- | :--- | :--- |
| [`Required`](https://pkg.go.dev/github.com/cinar/checker/v2#Required) | `required` | Ensures the value is provided |
| [`MinLen`](https://pkg.go.dev/github.com/cinar/checker/v2#MinLen) | `min-len:<n>` | Ensures the length of the given value (string, slice, or map) is at least n |
| [`MaxLen`](https://pkg.go.dev/github.com/cinar/checker/v2#MaxLen) | `max-len:<n>` | Ensures the length of the given value (string, slice, or map) is at most n |
| [`Len`](https://pkg.go.dev/github.com/cinar/checker/v2#Len) | `len:<n>` | Ensures the length of the given value (string, slice, or map) is exactly n |
| [`IsGte`](https://pkg.go.dev/github.com/cinar/checker/v2#IsGte) | `gte:<n>` | Ensures the value is greater than or equal to the specified number |
| [`IsLte`](https://pkg.go.dev/github.com/cinar/checker/v2#IsLte) | `lte:<n>` | Ensures the value is less than or equal to the specified number |
| [`IsGt`](https://pkg.go.dev/github.com/cinar/checker/v2#IsGt) | `gt:<n>` | Ensures the value is strictly greater than the specified number |
| [`IsLt`](https://pkg.go.dev/github.com/cinar/checker/v2#IsLt) | `lt:<n>` | Ensures the value is strictly less than the specified number |
| [`IsOneOf`](https://pkg.go.dev/github.com/cinar/checker/v2#IsOneOf) | `oneof:<v1>,<v2>,...` | Ensures the value equals one of a comma-separated list of allowed values |
| [`IsEq`](https://pkg.go.dev/github.com/cinar/checker/v2#IsEq) | `eq:<value>` | Ensures the value equals the given literal value |
| [`IsNe`](https://pkg.go.dev/github.com/cinar/checker/v2#IsNe) | `ne:<value>` | Ensures the value does not equal the given literal value |
| [`IsInt`](https://pkg.go.dev/github.com/cinar/checker/v2#IsInt) | `int` | Ensures the value is a whole number, with no fractional part |
| [`IsPositive`](https://pkg.go.dev/github.com/cinar/checker/v2#IsPositive) | `positive` | Ensures the value is strictly greater than zero |
| [`IsNegative`](https://pkg.go.dev/github.com/cinar/checker/v2#IsNegative) | `negative` | Ensures the value is strictly less than zero |
| [`IsNonnegative`](https://pkg.go.dev/github.com/cinar/checker/v2#IsNonnegative) | `nonnegative` | Ensures the value is greater than or equal to zero |
| [`IsMultipleOf`](https://pkg.go.dev/github.com/cinar/checker/v2#IsMultipleOf) | `multiple-of:<n>` | Ensures the value is a multiple of n, within a small floating-point tolerance |Frequently Asked Questions
What is checker?
checker is a Validation library for the Go programming language. Zero-dependency input validation and in-place normalization with struct tags, 23 locales, and JSON Schema generation
How do I install checker?
Install checker with the Go module system using `go get cinar/checker`. Check the repository for the current installation instructions.
What category does checker belong to?
checker is listed under Validation, specifically Validation.