VOOZH about

URL: https://deepwiki.com/hypervel/validation/4.2-built-in-rule-objects

⇱ Built-in Rule Objects | hypervel/validation | DeepWiki


Loading...
Menu

Built-in Rule Objects

This page documents the concrete rule object classes provided by the validation package. These objects offer fluent, chainable APIs for complex validation scenarios that require configuration beyond simple string-based rules.

For information about creating custom rule objects, see Custom Validation Rules. For conditional rules like RequiredIf and ProhibitedIf, see Conditional and Dynamic Rules. For the interfaces that rule objects implement, see Rule Interfaces and Contracts.

Purpose and Scope

Built-in rule objects are pre-configured validation classes that encapsulate complex validation logic with fluent configuration APIs. Unlike simple string rules (e.g., 'required|email'), these objects provide type-safe method chaining for building sophisticated validation requirements. They are instantiated via the Rule facade (see Rule Facade and Factory) and integrate seamlessly with the core validation engine.

Rule Object Categories

The validation package provides rule objects in four distinct categories:


Sources: src/Rules/Email.php17 src/Rules/Password.php19 src/Rules/File.php20 src/Rules/AnyOf.php13 src/Rules/Contains.php14 src/Rules/DoesntContain.php14

CategoryRule ObjectsPrimary Use Case
Format ValidationEmailValidating email addresses with configurable RFC compliance, DNS checks, and spoof prevention
Security ValidationPasswordEnforcing password strength requirements including length, character types, and compromise checking
File ValidationFile, ImageFileValidating uploaded files by MIME type, extension, and size constraints
Logical RulesAnyOfApplying "OR" logic across multiple validation rules
String Content RulesContains, DoesntContainChecking for presence or absence of specific values in strings

Common Implementation Patterns

Internal Validator Delegation

Most rule objects implement validation by creating internal Validator instances rather than implementing validation logic directly. This pattern allows them to leverage existing validation rules while providing a fluent configuration API:


Sources: src/Rules/Email.php166-188 src/Rules/Password.php251-301 src/Rules/File.php211-227 src/Rules/AnyOf.php36-52

Interface Implementation Pattern

Rule objects typically implement three core interfaces:

InterfacePurposeMethods Required
RuleCore validation contractpasses(string $attribute, mixed $value): bool
message(): array|string
DataAwareRuleAccess to all validation datasetData(array $data): static
ValidatorAwareRuleAccess to parent validatorsetValidator(ValidatorContract $validator): static

These interfaces enable rule objects to access validation context, including other field values and custom messages from the parent validator.

Sources: src/Rules/Email.php17 src/Rules/Email.php241-256 src/Rules/Password.php19 src/Rules/Password.php151-166

Defaults Configuration Pattern

Several rule objects support application-wide default configurations via the static defaults() method:


Sources: src/Rules/Email.php59-93 src/Rules/Password.php88-130 src/Rules/File.php70-104

Email Rule Object

The Email class provides configurable email validation with multiple validation strategies including RFC compliance checking, DNS record validation, and spoof prevention.

Configuration Methods

MethodDescriptionDelegate To
rfcCompliant(bool $strict = false)Enable RFC 5321/5322 compliance checkingemail:rfc or email:strict
strict()Enable strict RFC compliance (alias for rfcCompliant(true))email:strict
validateMxRecord()Verify MX DNS records exist for the domainemail:dns
preventSpoofing()Check for invalid unicode characters that could spoof addressesemail:spoof
withNativeValidation(bool $allowUnicode = false)Use PHP's filter_var() for validationemail:filter or email:filter_unicode
rules(array|string $rules)Add custom validation rules to be mergedAdditional rules array

Sources: src/Rules/Email.php98-161

Validation Process

The Email object builds a composite validation string based on its configuration and creates an internal validator:


Sources: src/Rules/Email.php166-188 src/Rules/Email.php193-228

Context-Aware Validation

The Email class implements DataAwareRule and ValidatorAwareRule, allowing it to access the parent validator's custom messages and attributes:


Sources: src/Rules/Email.php174-179 src/Rules/Email.php241-256

Password Rule Object

The Password class enforces password strength requirements with configurable character type requirements, length constraints, and compromise checking via breach databases.

Configuration Methods

MethodParametersDescription
min(int $size)$size - Minimum lengthStatic constructor, sets minimum password length (default: 8)
max(int $size)$size - Maximum lengthSets maximum password length
mixedCase()NoneRequires at least one uppercase and one lowercase letter
letters()NoneRequires at least one letter (any case)
numbers()NoneRequires at least one numeric digit
symbols()NoneRequires at least one symbol character
uncompromised(int $threshold = 0)$threshold - Allowed occurrences in breachesChecks against breach databases via UncompromisedVerifier
rules(array|Closure|Rule|string $rules)$rules - Additional rulesAdds custom validation rules

Sources: src/Rules/Password.php171-246

Validation Strategy

The Password class uses a two-phase validation approach:

  1. Basic Validation: Delegates to built-in string rules (string, min, max)
  2. Custom Checks: Uses regex patterns and compromise verification

Sources: src/Rules/Password.php251-301 src/Rules/Password.php265-298

Static Helper Methods

The Password class provides convenience static methods for common patterns:


Sources: src/Rules/Password.php135-146

Applied Rules Inspection

The appliedRules() method returns the current configuration state, useful for testing or debugging:

Sources: src/Rules/Password.php324-337

File Rule Object

The File class validates uploaded files by MIME type, file extension, and size constraints. It supports human-readable size formats (e.g., '2MB', '500KB').

Configuration Methods

MethodParametersDescription
types(array|string $mimetypes)$mimetypes - Allowed MIME types or extensionsStatic constructor, restricts allowed file types
extensions(array|string $extensions)$extensions - Allowed file extensionsRestricts by file extension
size(int|string $size)$size - Exact size in KB or human-readableRequires exact file size
between(int|string $minSize, int|string $maxSize)Size rangeRequires file size within range
min(int|string $size)$size - Minimum sizeSets minimum file size
max(int|string $size)$size - Maximum sizeSets maximum file size
rules(array|string|Stringable $rules)$rules - Additional rulesAdds custom validation rules

Sources: src/Rules/File.php119-206

Size Conversion System

The toKilobytes() method converts human-readable size strings to kilobytes:


Sources: src/Rules/File.php179-196

Rule Building Process

The buildValidationRules() method assembles validation rules based on configuration:


Sources: src/Rules/File.php232-280

ImageFile Subclass

The File::image(bool $allowSvg = false) static method creates an ImageFile instance, which extends File with image-specific validation:

Sources: src/Rules/File.php109-112

AnyOf Rule Object

The AnyOf class implements "OR" logic, passing validation if the value satisfies any one of the provided rules. This enables flexible validation where multiple valid formats are acceptable.

Implementation Architecture


Sources: src/Rules/AnyOf.php36-52

Usage Pattern

The AnyOf rule creates a nested validator for each rule alternative, inheriting custom messages and attributes from the parent validator:


Sources: src/Rules/AnyOf.php39-44

Contains and DoesntContain Rules

The Contains and DoesntContain classes are string-based rules (implementing Stringable) that check for the presence or absence of specific values within string attributes.

Implementation Pattern

Unlike other rule objects, these classes do not implement the Rule interface. Instead, they implement Stringable and convert to validation strings:


Sources: src/Rules/Contains.php24-45 src/Rules/DoesntContain.php24-45

Enum Support

Both rules support PHP enums (including UnitEnum and BackedEnum) via the enum_value() helper function, which extracts the underlying value:

Sources: src/Rules/Contains.php12 src/Rules/Contains.php39 src/Rules/DoesntContain.php12 src/Rules/DoesntContain.php39

String Escaping

Values are properly escaped to prevent injection issues:


This ensures values containing commas or quotes are safely embedded in the rule string.

Sources: src/Rules/Contains.php41 src/Rules/DoesntContain.php41

Rule Object Lifecycle

The following diagram illustrates the complete lifecycle of a rule object from instantiation through validation:


Sources: src/Rules/Email.php166-188 src/Rules/Email.php241-256 src/Rules/Password.php151-166 src/Rules/File.php307-322

Summary Table

Rule ClassPrimary PurposeKey InterfacesValidation Strategy
EmailEmail format validation with RFC/DNS/spoof checkingRule, DataAwareRule, ValidatorAwareRuleDelegates to email rule with parameters
PasswordPassword strength enforcementRule, DataAwareRule, ValidatorAwareRuleString rules + custom regex + breach checking
FileFile upload validationRule, DataAwareRule, ValidatorAwareRuleDelegates to file, mimes, mimetypes, size rules
ImageFileImage file validationInherits from FileExtends File with image-specific constraints
AnyOfLogical OR across rulesRule, ValidatorAwareRuleCreates validator for each rule, passes if any succeed
ContainsString contains valuesStringableConverts to 'contains:val1,val2' string rule
DoesntContainString doesn't contain valuesStringableConverts to 'doesnt_contain:val1,val2' string rule

Sources: src/Rules/Email.php17 src/Rules/Password.php19 src/Rules/File.php20 src/Rules/AnyOf.php13 src/Rules/Contains.php14 src/Rules/DoesntContain.php14