Skip to content

fix: execute runValidationWhenNil validators on untyped nil values - #1658

Open
AdamMagued wants to merge 1 commit into
go-playground:masterfrom
AdamMagued:fix-806-call-validation-when-nil-invalid-kind
Open

AdamMagued wants to merge 1 commit into
go-playground:masterfrom
AdamMagued:fix-806-call-validation-when-nil-invalid-kind

Conversation

@AdamMagued

Copy link
Copy Markdown

Summary

When validating untyped nil values (such as data[field] == nil in ValidateMap or Var(nil, tag)), the field value's kind is reflect.Invalid.

Previously, traverseField checked if kind == reflect.Invalid and immediately appended a field validation error and returned without checking ct.runValidationWhenNil.

This caused custom validators registered with callValidationEvenIfNull: true (and cross-field validators with nilCheckable: true such as required_if, required_unless, and excluded_if) to be bypassed whenever a field had an untyped nil value, erroneously reporting validation failures.

Changes

  1. Unify reflect.Invalid with nullable handling in traverseField:
    • Check !ct.runValidationWhenNil before reporting an error when kind is reflect.Invalid, allowing custom validators and cross-field validators to execute as intended.
    • For typeOmitNil, treat reflect.Invalid as nil and return early.
  2. Safe reflection on invalid values:
    • Ensure typ = current.Type() is only executed when current.IsValid(), avoiding panics.
    • Ensure getValue(val) returns nil when !val.IsValid(), avoiding panics on val.CanInterface().
  3. Regression Tests:
    • Added TestIssue806 in validator_test.go verifying ValidateMap, Var, custom failure reporting, and cross-field validation (required_if) on untyped nil values.

Fixes #806

When validating untyped nil values (such as data[field] == nil in ValidateMap or Var(nil, tag)), the field kind is reflect.Invalid. Previously, traverseField prematurely created a field error and returned without checking ct.runValidationWhenNil.

This prevented custom validators registered with callValidationEvenIfNull: true (and built-in cross-field validators like required_if/required_unless/excluded_if) from running when a field contained an untyped nil value.

This change:
- Unifies reflect.Invalid handling with nullable types so ct.runValidationWhenNil is respected.
- Safely handles reflect.Invalid in getValue and typeOmitNil.
- Ensures current.Type() is only called when current.IsValid() to prevent panics.
- Adds regression tests for ValidateMap and Var with untyped nil values.

Fixes go-playground#806
@AdamMagued
AdamMagued requested a review from a team as a code owner October 1, 2026 22:07
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.

Custom rule function isn't called with callValidationEvenIfNull: true

1 participant