VOOZH about

URL: https://deepwiki.com/hypervel/validation/4.4-conditional-and-dynamic-rules

⇱ Conditional and Dynamic Rules | hypervel/validation | DeepWiki


Loading...
Menu

Conditional and Dynamic Rules

Purpose and Scope

This document explains the conditional validation rule system in hypervel/validation, which enables validation rules to be applied or modified based on runtime conditions and the data being validated. This includes object-based conditional rules like ProhibitedIf and ExcludeIf, as well as string-based conditional rules like required_if, exclude_unless, and their variants.

For information about creating custom validation rules using closures or rule classes, see page 4.3. For the rule contract interfaces, see page 4.5. For built-in validation rules, see page 3.2.


Overview

The validation package provides conditional validation through two primary mechanisms:

MechanismExamplesKey Feature
Object-Based Conditional RulesProhibitedIf, ExcludeIfEvaluate condition and convert to string rule or empty string
String-Based Conditional Rulesrequired_if, exclude_unless, prohibited_ifInclude other field names as parameters for runtime evaluation

Both mechanisms allow validation behavior to change based on the values of other fields in the data being validated.

Sources: src/Rules/ProhibitedIf.php1-37 src/Rules/ExcludeIf.php1-37 src/Validator.php195-236


Object-Based Conditional Rules

Architecture

Object-based conditional rules like ProhibitedIf and ExcludeIf implement the Stringable interface to dynamically convert themselves into string rules based on a condition. This allows the rule to be evaluated during rule parsing and converted to a standard string rule (or empty string) before validation execution.

Title: Object-Based Conditional Rule Flow


Sources: src/Rules/ProhibitedIf.php10-36 src/Rules/ExcludeIf.php10-36

ProhibitedIf Class

The ProhibitedIf class conditionally applies the prohibited rule based on a boolean or closure condition.

Class structure:

PropertyTypeDescription
$conditionbool|ClosureThe condition that determines if the attribute should be prohibited

Methods:

MethodReturn TypeDescription
__construct(bool|Closure $condition)-Creates a new prohibited validation rule based on a condition
__toString()stringReturns 'prohibited' if condition is true, empty string otherwise

Title: ProhibitedIf Evaluation Logic


Sources: src/Rules/ProhibitedIf.php10-36

ExcludeIf Class

The ExcludeIf class conditionally applies the exclude rule based on a boolean or closure condition.

Class structure:

PropertyTypeDescription
$conditionbool|ClosureThe condition that determines if the attribute should be excluded

Methods:

MethodReturn TypeDescription
__construct(bool|Closure $condition)-Creates a new exclude validation rule based on a condition
__toString()stringReturns 'exclude' if condition is true, empty string otherwise

The ExcludeIf class follows the exact same pattern as ProhibitedIf, but returns 'exclude' instead of 'prohibited' when the condition evaluates to true.

Sources: src/Rules/ExcludeIf.php10-36

Condition Evaluation

Both classes evaluate their condition in the __toString() method:

Title: Condition Evaluation Strategy


Evaluation logic:

Sources: src/Rules/ProhibitedIf.php28-35 src/Rules/ExcludeIf.php28-35


String-Based Conditional Rules

Dependent Rules Classification

The Validator class maintains a list of dependent rules that reference other fields in their parameters. These rules are processed specially to handle field wildcards and cross-field validation.

Title: Dependent Rules in Validator


Sources: src/Validator.php195-236

Common Conditional Rule Patterns

String-based conditional rules follow several patterns based on their purpose:

PatternRulesParameter FormatBehavior
Field existencerequired_if, prohibited_if, exclude_iffield,valueApply rule if other field equals value
Field absencerequired_unless, prohibited_unless, exclude_unlessfield,valueApply rule unless other field equals value
Field presencerequired_with, present_with, exclude_withfield1,field2,...Apply rule if any listed field is present
All fields presentrequired_with_all, present_with_allfield1,field2,...Apply rule if all listed fields are present
Field absencerequired_without, exclude_withoutfield1,field2,...Apply rule if any listed field is absent
All fields absentrequired_without_allfield1,field2,...Apply rule if all listed fields are absent
Acceptance staterequired_if_accepted, required_if_declinedfieldApply rule based on field's accepted/declined state

Sources: src/Validator.php195-236

Exclude Rules

The Validator maintains a separate list of rules that can exclude attributes from validated data:

Title: Exclude Rules Flow


When an exclude rule is triggered:

  1. addFailure() checks if the rule is in excludeRules array src/Validator.php837-839
  2. If true, calls excludeAttribute() to mark attribute for exclusion src/Validator.php838
  3. Attribute is added to excludeAttributes array src/Validator.php859-863
  4. During validation, shouldBeExcluded() checks if attribute should be removed src/Validator.php454-465
  5. Excluded attributes are removed from validation data src/Validator.php470-474

Sources: src/Validator.php243 src/Validator.php837-839 src/Validator.php859-863


Integration with Validator

Validation Processing Flow

Title: Conditional Rule Processing in Validator


Sources: src/Validator.php288-305 src/Validator.php1066-1085 src/Validator.php554-606

Dependent Rule Parameter Processing

When a dependent rule is encountered, the Validator performs special parameter processing to handle wildcard field references:

Title: Dependent Rule Parameter Resolution


Processing steps:

  1. Check if rule is in dependentRules array src/Validator.php567
  2. Replace escaped dots with placeholder src/Validator.php568
  3. Extract explicit keys from attribute if wildcards exist src/Validator.php570
  4. Replace asterisks in parameters with actual keys src/Validator.php571
  5. Execute validation method with resolved parameters src/Validator.php603-605

Sources: src/Validator.php567-573 src/Validator.php609-614 src/Validator.php661-668

Implicit Rules Handling

Many conditional rules are also implicit rules, meaning they should be evaluated even if the attribute is absent from the data:

Title: Implicit Rule Classification


The isImplicit() method checks if a rule should validate even when attribute is absent:

This allows conditional rules like required_if to be evaluated even when the field doesn't exist in the data.

Sources: src/Validator.php163-188 src/Validator.php699-705


Usage Patterns

ProhibitedIf Usage

Title: ProhibitedIf Usage Pattern


Common scenarios:

ScenarioCondition TypeExample Use Case
Static prohibitionBoolean trueAlways prohibit a field: new ProhibitedIf(true)
Conditional prohibitionBoolean falseNever prohibit (no-op): new ProhibitedIf(false)
Dynamic prohibitionClosureProhibit based on logic: new ProhibitedIf(fn() => someCondition())

Sources: src/Rules/ProhibitedIf.php10-36

ExcludeIf Usage

Title: ExcludeIf Usage Pattern


Common scenarios:

ScenarioCondition TypeExample Use Case
Static exclusionBoolean trueAlways exclude field: new ExcludeIf(true)
No exclusionBoolean falseNever exclude (no-op): new ExcludeIf(false)
Dynamic exclusionClosureExclude based on logic: new ExcludeIf(fn() => shouldExclude())

Sources: src/Rules/ExcludeIf.php10-36

String-Based Conditional Rule Patterns

String-based conditional rules are specified as strings with parameters in the rules array:

Common string-based conditional rules:

Rule StringParametersWhen Applied
required_if:field,valueOther field name and valueAttribute required if other field equals value
required_unless:field,valueOther field name and valueAttribute required unless other field equals value
required_with:field1,field2Field namesAttribute required if any listed field is present
required_without:field1,field2Field namesAttribute required if any listed field is absent
prohibited_if:field,valueOther field name and valueAttribute prohibited if other field equals value
exclude_if:field,valueOther field name and valueAttribute excluded if other field equals value
exclude_unless:field,valueOther field name and valueAttribute excluded unless other field equals value

These rules are processed by their corresponding validate{Rule}() methods in the ValidatesAttributes trait.

Sources: src/Validator.php195-236


Practical Examples

Example 1: ProhibitedIf with Closure

Scenario: Prohibit a secondary email field if the user has not verified their primary email.

Title: ProhibitedIf Closure Example


Implementation: The closure can access external variables or perform complex logic to determine whether the field should be prohibited. When the closure returns true, the __toString() method returns 'prohibited', causing the field to fail validation if it has a value.

Sources: src/Rules/ProhibitedIf.php30-31

Example 2: ExcludeIf with Boolean

Scenario: Exclude internal metadata field when user role is not admin.

Title: ExcludeIf Boolean Example


Implementation: The boolean condition determines whether to exclude the field. When true, the field is marked for exclusion and removed from the final validated data, regardless of whether it passes other validation rules.

Sources: src/Rules/ExcludeIf.php34 src/Validator.php837-839

Example 3: String-Based required_if Rule

Scenario: Password confirmation is required only if password field is present.

Title: required_if Processing Flow


Implementation: The required_if rule is identified as a dependent rule, causing parameter processing to resolve any wildcards. The validation method then checks if the referenced field exists in the data and applies the required validation accordingly.

Sources: src/Validator.php195-236 src/Validator.php567-573


Example 4: Wildcard Parameter Resolution

Scenario: Require each array item to be different from its corresponding item in another array.

Title: Wildcard Resolution in Dependent Rules


Implementation: When validating values.0 with rule different:others.*, the validator:

  1. Detects the rule is dependent src/Validator.php567
  2. Extracts key [0] from attribute values.0 src/Validator.php570
  3. Replaces * in others.* with 0 to get others.0 src/Validator.php571
  4. Validates that values.0 differs from others.0

Sources: src/Validator.php567-573 src/Validator.php621-632 src/Validator.php661-668


Key Characteristics

Object-Based vs String-Based Rules

AspectObject-Based (ProhibitedIf, ExcludeIf)String-Based (required_if, exclude_unless)
DefinitionInstantiate rule objectsString with parameters
Condition evaluationIn __toString() during parsingDuring validation execution
Parameter formatSingle bool or ClosureField names and values as string parameters
FlexibilityArbitrary closure logicLimited to built-in condition types
Validation methodConverts to string ruleDirect method in ValidatesAttributes

Sources: src/Rules/ProhibitedIf.php28-35 src/Rules/ExcludeIf.php28-35 src/Validator.php195-236

Exclusion Mechanism

Exclude rules follow a special flow that removes attributes from validated data:

Title: Exclusion Processing Steps


Key points:

Sources: src/Validator.php53 src/Validator.php454-465 src/Validator.php470-474 src/Validator.php837-839

Implicit Rule Behavior

Conditional rules that check for field presence (required_if, present_if, missing_if) are classified as implicit rules:

Implicit rule characteristics:

This allows rules like required_if to determine whether a missing field should fail validation.

Sources: src/Validator.php163-188 src/Validator.php673-683 src/Validator.php699-705


Sources Summary

Primary implementation files:

Integration points: