Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ and a conversion that doesn't fit the field doesn't compile:
- **Conditions and custom rules**: `When` and `Custom` on fields and on the struct, closures with the context of the request — the limits can come from a database or the settings of a tenant.
- **Absent values**: nil pointers and the fields of nil nested structs are skipped by every rule except `Required`.
- **Your types**: a conversion function of a few lines, the core has no dependencies on uuid or other packages of types.
- **Tags of go-playground/validator**: `b.Tags("validate")` configures the rules of `validate:"required,max=64"` with the messages and the speed of valigo, a migration moves them to code one by one.

# Errors and translations
* Every error has the translated message, the location (`Tags[1]`, `address.city` with JSON paths), the value, a stable `Code` and named `Params`
Expand All @@ -91,5 +92,3 @@ The same struct and rules, Intel Core i9-14900HX, Go 1.27.0, see [Performance](h
| go-playground/validator | 1 785 ns, 16 allocs | 4 150 ns, 69 allocs, with `Error()` |
| ozzo-validation | 2 950 ns, 38 allocs | 12 665 ns, 140 allocs, with `Error()` |

# Roadmap
* [ ] Rules from tags
28 changes: 28 additions & 0 deletions bench/bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,13 @@ func newValigo() *valigo.Validator {
return v
}

// newValigoTags configures valigo by the tags of go-playground/validator.
func newValigoTags() *valigo.Validator {
v := valigo.New()
valigo.Configure[User](v, func(b valigo.Configurator[User], _ *User) { b.Tags("validate") })
return v
}

func TestTheSameRules(t *testing.T) {
ctx := context.Background()
v, pg := newValigo(), playground.New()
Expand All @@ -76,6 +83,13 @@ func TestTheSameRules(t *testing.T) {
if errs := v.Validate(ctx, invalid); len(errs) != 6 {
t.Errorf("valigo: %d errors: %v", len(errs), errs)
}
tags := newValigoTags()
if errs := tags.Validate(ctx, valid); errs != nil {
t.Errorf("valigo tags: %v", errs)
}
if errs := tags.Validate(ctx, invalid); len(errs) != 6 {
t.Errorf("valigo tags: %d errors: %v", len(errs), errs)
}
if errs, _ := pg.Struct(invalid).(playground.ValidationErrors); len(errs) != 6 {
t.Errorf("go-playground/validator: %d errors: %v", len(errs), errs)
}
Expand All @@ -93,6 +107,13 @@ func BenchmarkValid(b *testing.B) {
_ = v.Validate(ctx, valid)
}
})
b.Run("valigo-tags", func(b *testing.B) {
v := newValigoTags()
b.ReportAllocs()
for b.Loop() {
_ = v.Validate(ctx, valid)
}
})
b.Run("go-playground", func(b *testing.B) {
v := playground.New()
b.ReportAllocs()
Expand All @@ -117,6 +138,13 @@ func BenchmarkInvalid(b *testing.B) {
_ = v.Validate(ctx, invalid)
}
})
b.Run("valigo-tags", func(b *testing.B) {
v := newValigoTags()
b.ReportAllocs()
for b.Loop() {
_ = v.Validate(ctx, invalid)
}
})
b.Run("go-playground", func(b *testing.B) {
v := playground.New()
b.ReportAllocs()
Expand Down
1 change: 1 addition & 0 deletions docs/features/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ How the rules are configured and composed.
| [Conditions](conditions.md) | `When` on the struct and on a field, conditional requiredness |
| [Custom rules](custom.md) | `Custom` on a field, on a slice and on the struct, rules with limits from data |
| [Rules on other fields](fields.md) | `EqualField`, `MinField`, `MaxField`, `BeforeField`, `AfterField` by the pointer of the other field |
| [Rules from tags](tags.md) | `Tags`: the tags of go-playground/validator, `validate:"required,max=64"`, for a migration |

## Rules

Expand Down
83 changes: 83 additions & 0 deletions docs/features/tags.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# Rules from tags

`b.Tags("validate")` configures the rules of the tags of the fields of the struct and of its nested structs in the syntax of [go-playground/validator](https://github.com/go-playground/validator): `validate:"required,max=64"`. It is for a migration: the structs keep their tags, and the rules move to code one by one — the tags and the rules in code are mixed in one `Configure`.

The rules of the tags are the rules of valigo: the same messages in the languages of the users, the [codes](errors.md#codes-for-clients), the [JSON Schema](schema.md) and the speed — a valid object is validated without allocations, see [Performance](../performance.md).

## Example

```go
package main

import (
"context"
"fmt"

"github.com/insei/valigo"
"github.com/insei/valigo/str"
)

type Address struct {
City string `validate:"required,max=32"`
}

type SignUp struct {
Email string `validate:"required,email"`
Password string `validate:"required,min=8"`
Confirm string `validate:"eqfield=Password"`
Age int `validate:"omitempty,gte=18,lte=120"`
Tags []string `validate:"max=3,dive,required,max=16"`
Address *Address // the rules of City apply when the address is present
Nick string
}

func main() {
v := valigo.New()
valigo.Configure[SignUp](v, func(b valigo.Configurator[SignUp], s *SignUp) {
b.Tags("validate")
// the rules in code with the tags
b.Field(&s.Nick).As(str.Of).Trim().Alphanumeric()
})

errs := v.ValidateTyped(context.Background(), &SignUp{
Email: "ann", Password: "secret", Confirm: "secrets", Age: 16, Tags: []string{"go", ""}, Nick: " a b ",
})
for _, err := range errs {
fmt.Println(err.Location, "-", err.Message, "-", err.Code)
}
}
```

Output:

```text
Email - Should be email address - string.email
Password - Cannot be shorter than 8 characters - string.min_runes
Confirm - Should be equal to Password - string.equal_field
Age - Cannot be less than 18 - number.min
Tags[1] - Should be fulfilled - string.required
Nick - Should contain only letters and digits - string.alphanumeric
```

## Rules

| Fields | Rules |
|---|---|
| all | `required`, `omitempty` — the next rules are skipped for the zero value |
| strings | `min`, `max`, `len` in characters, `eq`, `oneof=a b`, `startswith`, `endswith`, `contains`, `email`, `url`, `http_url`, `uuid`, `ip`, `ipv4`, `ipv6`, `hostname`, `hostname_rfc1123`, `alphanum`, `ascii`, `lowercase`, `uppercase`, `e164`, `base64`, `base64url`, `json`, `semver`, `cidr`, `mac`, `hexcolor`, `iso3166_1_alpha2`, `iso4217`, `credit_card`, `luhn_checksum`, `datetime=2006-01-02`, `eqfield` |
| numbers | `min`, `gte`, `max`, `lte`, `eq`, `oneof=1 2`, `latitude`, `longitude`, `gtefield`, `ltefield` |
| `bool` | `required`: `true` |
| `time.Time` | `required`, `gtfield`, `ltfield` |
| slices | `required`, `min`, `max`, `len` of the length, `unique`, `dive` — the next rules are the rules of the elements |
| maps | `required`, `min`, `max`, `len` of the length, `dive` — the next rules are the rules of the values of `map[string]V` |
| pointers to nested structs | `required`; the fields have their own tags |

Pointers to the values have the rules of the values, a nil pointer is absent. `eqfield`, `gtefield` and the other rules on fields take the name of a field of the same struct, or its nested field `Inner.Field`.

## Differences from go-playground/validator

- `required` is `Required` of valigo: a string is not empty, a number is not zero, a slice and a map have elements — go-playground/validator accepts an empty non-nil slice.
- The fields of a nil nested struct are skipped, like by go-playground/validator. The rules in code check `Required` of these fields, see [Absent values](absent.md).
- `dive` into the elements of structs, `keys`/`endkeys`, the alternatives `|`, `gt`/`lt` of numbers and the custom tags of go-playground/validator aren't supported: write these rules in code, with `When` and `Custom`.
- An unknown rule panics in `Configure`, like an invalid rule in code, so a typo doesn't turn into a missing check.
- The rules after `omitempty` aren't in the JSON Schema: they don't apply to every value.
1 change: 1 addition & 0 deletions docs/performance.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ An invalid object with 6 errors:

valigo is about 1.4 times slower than the same rules written by hand on a valid object, it pays for the closures of the rules; it doesn't allocate either. The fields are read by the offsets of fmap without reflect, following the pointers of nested structs. Code generators of validators produce code like the hand-written one, so they are expected to be about as fast as it.

- The [rules from tags](features/tags.md) are the same rules: in one run a valid object took 392 ns by the tags of go-playground/validator and 373 ns by the rules in code, 0 allocations both; `max=64` is `MaxRunes`, `gte` and `lte` are two rules instead of one `AnyOfInterval`.
- valigo builds the rules once in `Configure` and reads the fields by precomputed accessors, so valid objects cost no allocations; go-playground/validator parses the tags once too, but works through `reflect` on every call, ozzo-validation builds its rules on every call of `Validate`.
- gookit/validate creates a validation per call, it is its API, and reports the errors of the elements of a slice under one key `Tags.*`; zog builds the messages of its issues.
- valigo builds the translated messages of the errors at once, go-playground/validator returns the errors without messages and builds them by `Error` or `Translate`: compare valigo with the row "with `Error()`".
Expand Down
2 changes: 2 additions & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ nav:
- Conditions: features/conditions.md
- Custom rules: features/custom.md
- Rules on other fields: features/fields.md
- Rules from tags: features/tags.md
- Rules:
- Strings: features/strings.md
- Numbers: features/numbers.md
Expand Down Expand Up @@ -135,6 +136,7 @@ plugins:
- features/conditions.md: When on the struct and on fields, conditional requiredness
- features/custom.md: Custom rules, rules from data
- features/fields.md: rules on other fields
- features/tags.md: the rules of the tags of go-playground/validator, a migration from it
Rules:
- features/strings.md: the rules and formats of strings
- features/numbers.md: the rules of numbers
Expand Down
9 changes: 9 additions & 0 deletions shared/field.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,15 @@ func valueGetter[T any](field fmap.Field) func(obj any) *T {
}
}

// InStruct returns a function that reports whether the nested structs stored by pointer, which the field is in,
// are allocated in obj, a pointer to the configured struct: false for the fields of a nil nested struct.
func InStruct(field fmap.Field) func(obj any) bool {
addr := fieldAddr(field)
return func(obj any) bool {
return addr(dataPtr(obj)) != nil
}
}

// fieldAddr returns a function that computes the address of the field in the struct at root by the offsets of fmap,
// without reflect: the offset of a field is from the root struct or from the struct of its nearest ancestor stored
// by pointer, so the address follows the pointers of these ancestors. It returns nil if one of them is nil.
Expand Down
7 changes: 7 additions & 0 deletions shared/field_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -315,3 +315,10 @@ func TestCheckWithForeignPointerPanics(t *testing.T) {
NewValueField[string](sampleField(t, "Text"), pathHelper{}, sampleFields, r.add, nil).CheckWith(&foreign, func(string, string) bool { return true }, "bad")
})
}

func TestInStruct(t *testing.T) {
present := InStruct(sampleField(t, "Inner.Text"))
assert.True(t, present(&sample{Inner: &inner{}}))
assert.False(t, present(&sample{}))
assert.True(t, InStruct(sampleField(t, "Text"))(&sample{}))
}
4 changes: 4 additions & 0 deletions skills/valigo/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,10 @@ func main() {

`valigo.New(valigo.WithErrorsTransformer(problem.Transformer()))` makes `Validate` return one `*problem.Details` of RFC 9457, write it by `problem.From(errs).Write(w)`: 422, `application/problem+json`, `errors` with `detail`, `pointer` (`#/tags/1`), `location`, `code`, `params`. Options: `problem.WithType`, `WithTitle`, `WithStatus`, `WithDetail`.

## Rules from tags

`b.Tags("validate")` in `Configure` applies go-playground/validator tags (`required`, `min`/`max`/`len`, `oneof`, `email`, `url`, `uuid`, `gte`/`lte`, `eqfield`, `gtefield`, `dive`, `unique`, `omitempty`...) as valigo rules, mixable with code rules. Unknown rules, `|`, `keys`, dive into structs panic in Configure: write them in code. Fields of nil nested structs are skipped (unlike code rules).

## JSON Schema

`v.Constraints()` returns the unconditional rules as JSON Schema keywords (`shared.Constraint`: Struct, Field, Path `items`/`additionalProperties`/`propertyNames`, Keyword, Value); rules under `When` aren't described, after `Trim`/`Modify` only `required`. `vhuma.OpenAPI(api, v)` returns the huma document with them in the body schemas (huma's own schemas stay unchanged). Own conversions describe rules by `f.Schema("minimum", 0)`.
Expand Down
Loading
Loading