Regex Rule provides a simple, rule-based regular expression validation implementation for the Aegisora ecosystem.
It is built on top of aegisora/rule-contract and follows its strict validation architecture, ensuring consistent and predictable behavior across applications.
This rule is useful for validating user input, form fields, usernames, slugs, email addresses, phone numbers, API request parameters, and any other string that must match a specific pattern.
- Features
- Installation
- Core Concept
- Basic Usage
- Valid vs Invalid
- Validation Result
- Guardian Usage
- Real-World Examples
- Factory Methods
- Architecture
- License
- Contributing
- Support
- πΉ Lightweight and dependency-free except
aegisora/rule-contract - πΉ Validates a string against any PCRE regular expression
- πΉ Supports the full pattern syntax and flags (
i,u,m,s, ...) - πΉ Rejects non-string input as an invalid context
- πΉ Surfaces broken patterns and runtime PCRE failures as execution errors instead of a silent
false - πΉ Fully compatible with Aegisora validation pipeline
- πΉ Strict
ContextβResultvalidation flow - πΉ No raw booleans β only structured results
- πΉ Safe execution via base
Ruleabstraction - πΉ Expressive factory API
- πΉ Ready to use out of the box
composer require aegisora/regex-ruleThis package implements a single validation rule:
- accepts a string value via
Context - checks whether the string matches the configured regular expression
- returns a standardized
Result
Under the hood it wraps the common boilerplate:
if (preg_match($pattern, $value) !== 1) {
// value does not match the pattern
}into a reusable rule that reports its outcome through a Result object instead of a raw boolean, and turns PCRE failures into explicit exceptions.
use Aegisora\RuleContract\Models\Context;
use Aegisora\Rules\RegexRule;
$result = RegexRule::create('/^[a-z0-9_-]+$/')->validate(Context::create('user_name-1'));
if ($result->isValid()) {
// value matches the pattern
} else {
// value does not match the pattern
}The rule can also be instantiated directly:
$result = (new RegexRule('/^[a-z0-9_-]+$/'))->validate(Context::create('user_name-1'));The rule passes when the string matches the configured pattern and fails otherwise.
RegexRule::create('/^[a-z]+$/')->validate(Context::create('abc')); // valid β the whole string matches
RegexRule::create('/^[a-z]+$/')->validate(Context::create('abc123')); // invalid β digits are not allowed
RegexRule::create('/^\d+$/')->validate(Context::create('12345')); // valid β only digits
RegexRule::create('/^\d+$/')->validate(Context::create('')); // invalid β at least one digit is requiredRegexRule::create('/\d+/')->validate(Context::create('abc123')); // valid β a digit is found somewhere
RegexRule::create('/\d+/')->validate(Context::create('abcdef')); // invalid β no digit foundRegexRule::create('/^abc$/i')->validate(Context::create('ABC')); // valid β case-insensitive match
RegexRule::create('/^abc$/')->validate(Context::create('ABC')); // invalid β case matters without the i flag
RegexRule::create('/^[Π°-ΡΡ]+$/ui')->validate(Context::create('ΠΡΠΈΠ²Π΅Ρ')); // valid β u flag enables UTF-8 modeIf the string matches the pattern, the rule returns a valid result.
$result->isValid(); // true
If the string does not match the pattern, the rule returns an invalid result.
$result->isValid(); // false
$result->getFailedRuleCode(); // regex_ruleIf the context value is not a string, the rule throws:
Aegisora\RuleContract\Exceptions\InvalidRuleContextException
If the pattern is invalid, or the match fails at runtime (e.g. the backtrack limit is exceeded or the subject is not valid UTF-8 under the u flag), the rule throws:
Aegisora\RuleContract\Exceptions\RuleExecutionException
This rule can be used together with aegisora/guardian to build fluent validation pipelines.
use Aegisora\Guardian\Guardian;
use Aegisora\Rules\RegexRule;
use App\Exceptions\InvalidUsernameException;
$guardian = new Guardian();
$guardian
->that($username)
->must(RegexRule::create('/^[a-z0-9_-]{3,32}$/'), new InvalidUsernameException())
->validate();If the value does not match the pattern, Guardian throws the provided domain exception.
Regex Rule is useful for enforcing format constraints before values are persisted or processed.
Examples
User Registration:
require a username of lowercase letters, digits, underscores and hyphens
Slugs:
ensure a URL slug contains only lowercase letters, digits and hyphens
Identifiers:
validate that a code matches a fixed structured format
API:
reject request parameters that do not match the expected shape
RegexRule::create($pattern);
- creates a rule that passes when the value matches the PCRE
$pattern(delimiters and flags included)
new RegexRule($pattern);
- equivalent to
RegexRule::create($pattern)
RegexRule::create($pattern)->validate($context);
$contextβContextwrapping the string value to validate
This package relies on aegisora/rule-contract.
Flow:
validate()is calledContextis passed in- The configured pattern is checked; a broken pattern raises
RuleExecutionException - The string value is extracted from context (non-strings raise
InvalidRuleContextException) - The value is matched against the pattern with
preg_match(); a PCRE runtime failure raisesRuleExecutionException Resultis returned β valid on match, invalid with theregex_rulecode on no match
All logic is safely handled by Rule contract.
This package is open-source and licensed under the MIT License. See the LICENSE for details.
Contributions are welcome and greatly appreciated! See the CONTRIBUTING for details.
If you find this project useful, please consider giving it a star on GitHub!
It helps the project grow and motivates further development.