Fix embedded struct conditional validation - nested fields not respecting parent required_if conditions #304
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR fixes an issue where embedded struct fields with
json:",inline"
tags were being validated even when their parent embedded struct had conditional validation rules (likerequired_if
) that should have skipped the validation.Problem
When using embedded structs with conditional validation, nested fields were always validated regardless of whether the parent struct's condition was met:
The
UserData
struct hasvalidate:"required_if:Type,give"
meaning it should only be validated whenType
equals "give". However, whenType
was "remove", the nested fields (name
andbranch
) were still being validated and causing validation failures.Solution
Added logic in the validation flow to properly handle conditional validation for embedded structs:
Rule.Apply()
to check if a field belongs to an embedded struct with conditional validation before processingshouldSkipEmbeddedFieldValidation()
method that evaluates parent struct conditionsrequired_if
,required_unless
, and other conditional validatorsKey Changes
validating.go
: Added check for embedded field validation skipping inRule.Apply()
validation.go
: Added methods for evaluating conditional validator conditions:shouldSkipEmbeddedFieldValidation()
evaluateConditionalValidatorCondition()
evaluateRequiredIfCondition()
evaluateRequiredUnlessCondition()
Testing
required_unless
and other conditional validatorsAfter the fix:
Type="remove"
→ validation passes (nested fields skipped) ✅Type="give"
→ validation properly checks nested fields ✅Fixes #259.
✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.