Repository navigation
feat: SelfValidator for custom and cross-field validation - #25
Conversation
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.
501b3ef to
504231c
Compare
…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
left a comment
There was a problem hiding this comment.
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:
ExampleSelfValidatorbuilds the client with no validator (mg.NewClient(\"dgraph://localhost:9080\")) and expects theEnd < Startrule 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.
matthewmcneely
left a comment
There was a problem hiding this comment.
Also can we add a section in the README with the SelfValidator feature?
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
left a comment
There was a problem hiding this comment.
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.
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.
What this adds
SelfValidator, an opt-in seam that lets a type drive its own validation —building on the existing
StructValidatorsupport rather than replacing it.When a value passed to
Insert/Upsert/UpdateimplementsSelfValidator,the client calls
ValidateWithinstead of handing it straight to the configuredStructValidator. Plain structs are unaffected — they still flow throughStructCtxexactly 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:
End >= Start,password == confirm).SelfValidatoris the seam for those.ValidateWithreceives the configuredStructValidator, so an implementation can run ordinary tag-based validationfirst and layer custom logic on top:
validateStructroutes each element through avalidateOnehelper that detectsSelfValidator(on the value or its address) and otherwise falls back toStructCtx— unchanged behavior for ordinary structs.Tests
TestValidateRoutesToSelfValidator/TestValidateFallsBackToStructCtx—routing and the unchanged fallback.
TestValidateSelfValidatorInSlice— slice elements route correctly, and theconfigured
StructValidatoris not also invoked (strengthened this roundto 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
ExampleSelfValidatorshowing a cross-field rule that layers on theconfigured
StructValidator.