Skip to content

feat: SelfValidator for custom and cross-field validation - #25

Merged
matthewmcneely merged 4 commits into
matthewmcneely:mainfrom
mlwelles:feature/self-validation
Jul 1, 2026
Merged

matthewmcneely merged 4 commits into
matthewmcneely:mainfrom
mlwelles:feature/self-validation

Conversation

@mlwelles

@mlwelles mlwelles commented Jun 4, 2026 •

Copy link
Copy Markdown

What this adds

SelfValidator, an opt-in seam that lets a type drive its own validation —
building on the existing StructValidator support rather than replacing it.

type SelfValidator interface {
    ValidateWith(ctx context.Context, v StructValidator) error
}

When a value passed to Insert/Upsert/Update implements SelfValidator,
the client calls ValidateWith instead of handing it straight to the configured
StructValidator. Plain structs are unaffected — they still flow through
StructCtx exactly as before.

The problem it solves

Struct tags validate one field at a time. Plenty of real validation lives
outside what a tag can express:

  • Cross-field rules — one field constrained by another (End >= Start,
    password == confirm).
  • Conditional rules — field B required only when field A has some value.
  • Computed / setter-derived values — state that is not a plain tagged field.
  • Business rules — anything that needs real logic.

SelfValidator is the seam for those. ValidateWith receives the configured
StructValidator, so an implementation can run ordinary tag-based validation
first and layer custom logic on top:

func (e *Event) ValidateWith(ctx context.Context, v mg.StructValidator) error {
    if v != nil {
        if err := v.StructCtx(ctx, e); err != nil { // tag-based checks first
            return err
        }
    }
    if e.End < e.Start { // then the cross-field rule
        return fmt.Errorf("End (%d) must be >= Start (%d)", e.End, e.Start)
    }
    return nil
}

validateStruct routes each element through a validateOne helper that detects
SelfValidator (on the value or its address) and otherwise falls back to
StructCtx — unchanged behavior for ordinary structs.

Tests

  • TestValidateRoutesToSelfValidator / TestValidateFallsBackToStructCtx —
    routing and the unchanged fallback.
  • TestValidateSelfValidatorInSlice — slice elements route correctly, and the
    configured StructValidator is not also invoked (strengthened this round
    to assert the no-double-call, matching the scalar test).
  • TestSelfValidatorCustomCrossFieldRule — a concrete cross-field example.

The automated review (cubic) found no issues in the implementation.

Documentation

A runnable ExampleSelfValidator showing a cross-field rule that layers on the
configured StructValidator.

@mlwelles
mlwelles requested a review from matthewmcneely as a code owner June 4, 2026 20:14

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 2 files

Re-trigger cubic

Adds SelfValidator, an opt-in seam that lets a type drive its own
validation. When a value passed to Insert, Upsert, or Update implements
SelfValidator, the client calls ValidateWith instead of handing the value
straight to the configured StructValidator.

This covers validation that struct tags cannot express on their own:
cross-field rules (one field constrained by another), conditional rules,
checks on computed or setter-derived values, and broader business rules.
ValidateWith receives the configured StructValidator, so an implementation
can still run ordinary tag-based checks and layer custom logic on top.

validateStruct routes each element through a new validateOne helper that
detects SelfValidator (on the value or its address) and otherwise falls back
to StructCtx exactly as before — behavior is unchanged for ordinary structs.
@mlwelles
mlwelles force-pushed the feature/self-validation branch from 501b3ef to 504231c Compare June 4, 2026 20:45
@mlwelles mlwelles changed the title feat: SelfValidator for private-field validation feat: SelfValidator for custom and cross-field validation Jun 4, 2026
…d example

- TestValidateSelfValidatorInSlice now asserts the configured StructValidator
  is never called for a SelfValidator slice element, matching the scalar test;
  a regression invoking both paths would otherwise pass silently.
- Add a runnable ExampleSelfValidator showing a cross-field rule that layers
  on the configured StructValidator.

@matthewmcneely matthewmcneely left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice seam, and the routing itself is right — but there's a correctness gap that defeats the feature in its most common configuration.

P1: SelfValidator is silently skipped when no StructValidator is configured

validateStruct returns early on c.options.validator == nil (client.go:467), before validateOne runs. So a type's ValidateWith only fires if the client also has a StructValidator set via WithValidator. A client created without a validator — the default — never invokes SelfValidator at all.

This contradicts the feature's own design:

  • ExampleSelfValidator builds the client with no validator (mg.NewClient(\"dgraph://localhost:9080\")) and expects the End < Start rule to reject the event. With the current guard that rule is skipped. (The example has no // Output: line, so it compiles but never runs — which is why it doesn't fail CI.)
  • The PR description says "when a value passed to Insert/Upsert/Update implements SelfValidator, the client calls ValidateWith" — with no stated requirement that a StructValidator be configured.

I confirmed it empirically:

no-validator:   validateStruct(&entity{Bad:true}) -> <nil>          // SelfValidator SKIPPED
with-validator: validateStruct(&entity{Bad:true}) -> probe-rejected // runs

Why the tests miss it

Every unit test constructs client{options: clientOptions{validator: &recordingValidator{}}} — a validator is always present, so the no-validator path is never exercised. Please add a regression test that configures no validator and asserts ValidateWith still runs (and that a plain struct with no validator is still skipped).

Suggested fix

Move the nil check out of validateStruct and into validateOne's fallback, so a SelfValidator runs regardless while plain structs still skip when no validator is set:

if sv, ok := iface.(SelfValidator); ok {
    return sv.ValidateWith(ctx, c.options.validator) // v may be nil; impl guards
}
if c.options.validator == nil {
    return nil // plain struct, no configured validator -> skip as before
}
return c.options.validator.StructCtx(ctx, iface)

Note one deliberate behavior change with this: without a validator, a nil-pointer arg would now hit the existing "cannot validate nil pointer" error instead of being skipped. Insert already requires a non-nil pointer, so that seems more correct — flagging it so it's a conscious choice.

Secondary: README

The README documents WithValidator but has nothing on SelfValidator. Since the README is the project's only docs, please add a short subsection (a cross-field example layering on the configured validator).

What's already good

Routing and the no-double-call behavior are correct; addressability works for *T, []*T, and []T (slice elements are addressable, so a pointer-receiver ValidateWith is detected); and the fallback is unchanged for ordinary structs.

Comment thread client.go Resolved

@matthewmcneely matthewmcneely left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also can we add a section in the README with the SelfValidator feature?

mlwelles and others added 2 commits July 1, 2026 00:26
validateStruct returned early when no StructValidator was configured, so the
SelfValidator dispatch in validateOne never ran for the default client — the
feature was dead code for the common case. Move the nil check out of
validateStruct into validateOne's StructValidator fallback, after the
SelfValidator branch, so a self-validating type validates regardless of
whether a StructValidator was set.

Add default-client tests (no StructValidator): a SelfValidator, a slice of
SelfValidators, and a plain struct. The first two fail against the old
ordering; the plain case guards the nil StructValidator fallback.

Addresses review feedback from @matthewmcneely on PR #25.
Add a SelfValidator subsection under the validation docs showing the
layered pattern — run the configured StructValidator's tag-based checks
first, then apply cross-field or business rules. The README is the
project's only documentation.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

@matthewmcneely matthewmcneely left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 resolved and verified. The fix in 679160a is exactly right: the validator == nil early return moved out of validateStruct and into validateOne, after the SelfValidator branch — so a SelfValidator now runs on the default client, while a plain struct with no configured validator still skips.

I confirmed empirically against the current head:

  • no configured validator + SelfValidator -> ValidateWith runs (rejects as expected)
  • no configured validator + plain struct -> skipped cleanly

And the regression gap I flagged is now covered: TestValidateSelfValidatorRunsWithoutStructValidator, TestValidateSelfValidatorSliceRunsWithoutStructValidator, and TestValidatePlainEntitySkippedWithoutStructValidator all construct a client with validator: nil.

README: documented SelfValidator under the validation section (682c80f), showing the layered pattern (configured StructValidator's tag checks first, then cross-field/business rules).

CI green across the full suite.

@matthewmcneely
matthewmcneely merged commit 0ffc15a into matthewmcneely:main Jul 1, 2026
5 checks passed
matthewmcneely pushed a commit that referenced this pull request Jul 1, 2026
validateStruct returned early when no StructValidator was configured, so the
SelfValidator dispatch in validateOne never ran for the default client — the
feature was dead code for the common case. Move the nil check out of
validateStruct into validateOne's StructValidator fallback, after the
SelfValidator branch, so a self-validating type validates regardless of
whether a StructValidator was set.

Add default-client tests (no StructValidator): a SelfValidator, a slice of
SelfValidators, and a plain struct. The first two fail against the old
ordering; the plain case guards the nil StructValidator fallback.

Addresses review feedback from @matthewmcneely on PR #25.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants