Skip to content

Omega MVC — Validator Package Manual ​

The Omega\Validator package is a fluent validation and filtering library built on top of GUMP (wixel/gump). The concrete Validator class manages input fields, a ValidPool of validation rules and a FilterPool of filter rules. Rules and filters are composed fluently as Valid/Filter objects, then compiled to the GUMP rule strings. There is no ValidatorInterface and no validator facade — the entry points are Validator, the validate() helper, and the vr()/fr() rule builders.

The validator — Validator ​

php
use Omega\Validator\Validator;

$val = new Validator($_POST);
$val->name->required()->min_len(3);        // property-style rule
$val->field('email')->required()->valid_email();
$val('age')->required()->integer();        // invoke the validator
$val->field('password')->required()->equalsfield('password_confirmation');

if ($val->isValid()) {
    $clean = $val->filter_out(...);
}

make() is the static factory; closures receive the rule pools:

php
$val = Validator::make($input, function (ValidPool $valid) {
    $valid('name')->required()->max_len(100);
    $valid('email')->required()->valid_email();
}, function (FilterPool $filter) {
    $filter('name')->trim()->upper_case();
});

Public API ​

MethodDescription
field(string ...$field): Validstart building validation rules for a field
filter(string ...$field): Filterstart building filter rules for a field
fields(iterable $fields): selfset/replace the input array
get_fields(): arrayinput array
isValid($rule_validation = null): boolrun validation (optionally inline via closure)
is_error($rule_validation = null): boolinverted isValid()
getError(): arrayfield → message map (runs validation once)
errors(): Collectionsame as getError() as a Collection
if_valid($condition): ValidationConditionrun $condition when valid; chain ->else(fn ($errors) => ...) on failure
validOrException(?\Exception $exception = null): boolthrow (or the given exception) when invalid
validOrError(?\Exception $exception = null): bool|arraytrue or the error list
filter_out($rule_filter = null): arrayapply filters and return cleaned input
failedOrFilter(): array|boolfiltered array when valid, true when invalid
validation($pools): selfmerge rules from a ValidPool closure
filters($pools): selfmerge filters from a FilterPool closure
messages($pools = null): MessagePoolcustom per-field/rule messages via closure
setErrorMessages(array $messages): voidcustom messages as field => message map
lang(string $lang): selfGUMP validation message language
submitted(): booltrue when REQUEST_METHOD === 'POST'
passed(): boolisValid() && submitted()
fails(): boolinverted passed()
only(array $fields): self / except(array $fields): selfrestrict which fields are validated/filtered

Magic access is shorthand for common paths:

php
$val->email->required();            // same as $val->field('email')
$val->errors;                       // Collection (same as ->errors())
$val->filters;                      // Collection of filtered output
$val->email = 'required|min_len,5'; // same as ->field('email')->raw(...)

Validation rules — Valid ​

Build rules fluently; each method appends a GUMP rule. Parameters use , between a rule and its params and ; between array params; not inverts the next rule and if()/end_if()/where() gate rules by a closure.

php
$val->field('name')->required()->not->contains_list('a', 'b');
$val->field('status')->if(fn () => $editing)->required()->end_if();
$val->field('note')->where(fn () => $requiresNote)->min_len(2);

Shipped validation rules ​

RuleSignature
requiredrequired()
containscontains(string ...$values) — shows possible values in the message
contains_listcontains_list(string ...$values) — hides the list
doesnt_contain_listdoesnt_contain_list(string ...$values)
booleanboolean(bool $strict = true) — yes/no, on/off, 1/0, true/false; strict mode allows only true/false
valid_emailvalid_email()
max_lenmax_len(int $len)
min_lenmin_len(int $len)
exact_lenexact_len(int $len)
between_lenbetween_len(int $min, int $max)
alphaalpha()
alpha_numericalpha_numeric()
alpha_dashalpha_dash()
alpha_numeric_dashalpha_numeric_dash()
alpha_spacealpha_space()
alpha_numeric_spacealpha_numeric_space()
numericnumeric()
integerinteger()
floatfloat()
valid_urlvalid_url()
url_existsurl_exists()
valid_ipvalid_ip()
valid_ipv4valid_ipv4()
valid_ipv6valid_ipv6()
valid_ccvalid_cc() — credit card
valid_namevalid_name()
street_addressstreet_address()
ibaniban()
datedate(string $format) — format like d/m/Y
min_agemin_age(int $age) — input Y-m-d
max_numericmax_numeric(int $num)
min_numericmin_numeric(int $num)
startsstarts(string $startWith)
required_filerequired_file()
extensionextension(string ...$extension)
equalsfieldequalsfield(string $fieldName) — equals_field() is the v1 alias
guidv4guidv4()
phone_numberphone_number()
regexregex(string $regex)
valid_json_stringvalid_json_string()
valid_array_size_greatervalid_array_size_greater(int $size)
valid_array_size_lesservalid_array_size_lesser(int $size)
valid_array_size_equalvalid_array_size_equal(int $size)
valid(callable, string $message)custom closure validator
raw(string $rule)append a raw GUMP rule string
not()invert the next rule
if(callable) / end_if()apply the following rules only when the closure returns true
where(callable)reset all built rules when the closure returns false

Filter rules — Filter ​

Filters sanitize input; they run through filter_out() / failedOrFilter().

php
$val->filter('email')->trim()->sanitize_email();
$val->filter('bio')->lower_case()->basic_tags();
$val->filter('title')->slug();

Shipped filter rules ​

FilterSignature
noise_wordsnoise_words()
rmpunctuationrmpunctuation() — strip punctuation
urlencodeurlencode()
htmlencodehtmlencode()
sanitize_emailsanitize_email() — strip illegal email chars
sanitize_numberssanitize_numbers()
sanitize_floatssanitize_floats()
sanitize_stringsanitize_string() — strip script tags
booleanboolean() — ['1','1',true,'on'] → true, else false
basic_tagsbasic_tags() — keep a small safe HTML tag set
whole_numberwhole_number()
ms_word_charactersms_word_characters() — MS Word → web-safe chars
lower_caselower_case()
upper_caseupper_case()
slugslug()
trimtrim()
filter(callable $value, $params)custom closure filter
raw(string $rule)append a raw GUMP filter
if(callable) / end_if() / where(callable)conditional application

Custom rules ​

Register custom validators and filters inline as closures. Every valid() call registers a unique GUMP rule (random hex name) on Rule::add_validator() and records an invert companion; the failure message supports {field} placeholders.

php
$val = new Validator(['test' => 2]);

$val->field('test')->valid(
    fn ($field, $input, $param, $value) => $value % 2 === 1,
    '{field} must be an odd number',
);

$val->not->field('test')->valid(fn ($field, $input, $param, $value) => ...); // inverted

$val->filter('tag')->filter(fn ($value, $params) => strtoupper($value));

if ($val->isValid()) { /* ... */ }

Non-boolean conditions inside if()/where() throw Exception (Condition closure not return boolean).

Error messages and attributes ​

Errors are exposed as field => message. Default messages come from GUMP and are switchable with lang(); custom messages can target a field, a rule, or both:

php
$val->messages(function (MessagePool $messages) {
    $messages->email->validemail('Please provide a valid email.');
    $messages->set('name', (new Message())->add(['required' => 'Please set your name.']));
});

$val->setErrorMessages([
    'email' => ['validemail' => 'Bad email format.'],
]);

$val->errors;               // Collection<string, string>
$val->errors->all();        // ['email' => 'Bad email format.', ...]

MessagePool keys fields and returns Message objects; Message is ArrayAccess over rule → message and implements ValidationPropertyInterface (purely a doc-holder for the @property rule names).

Inline validation and conditions ​

php
$val->isValid(function (ValidPool $valid) {
    $valid('name')->required()->max_len(7);
    $valid('nest.number')->required();
    $valid('users.*.name')->required();      // wildcard path
});

$val->if_valid(function () use ($request) {
    $this->save($clean);
})->else(function (array $errors) {
    return $errors;
});

Helper functions ​

php
use function Omega\Validator\validate;
use function Omega\Validator\vr;
use function Omega\Validator\fr;

$val   = validate($_POST);                 // new Validator($input)
$valid = vr();                             // new Valid (fluent rule builder)
$filt  = fr();                             // new Filter (fluent filter builder)

Exceptions ​

The package has no dedicated exception classes. Failures surface as PHP or GUMP exceptions:

ExceptionWhen thrown
\ExceptionvalidOrException() with no/lacking validation — default Exception("vaildate if fallen", 1) or the supplied instance (source spelling)
\ExceptionValid::if()/where() or Filter::if()/where() closures not returning a boolean (Condition closure not return boolean)
Random\RandomExceptionValid::valid() / Filter::filter() random rule-name generation fails

Notes ​

  • Rules are lazily compiled to GUMP pipe strings: required|min_len,5, contains,foo;bar. get_validation()/__toString() on Valid exposes the compiled string.
  • Validation is cached per validator via has_run_validate, and getError() runs the checks only once.
  • tests/Feature/Validator/ holds the non-mirrored integration suite (nested arrays, wildcards, invert and one-line validate+filter); unit suites live in tests/Unit/Validator/.

Reference ​

  • Validator.php, Rule.php (extends \GUMP), ValidationCondition.php
  • Rule/Valid.php, Rule/ValidPool.php, Rule/Filter.php, Rule/FilterPool.php
  • Messages/Message.php, Messages/MessagePool.php
  • Traits/InvertValidationTrait.php, Traits/CustomValidationTrait.php, Traits/CustomFilterTrait.php
  • Contract/ValidationPropertyInterface.php, Contract/FilterPropertyInterface.php
  • helper.php (validate(), vr(), fr())
  • Tests: tests/Unit/Validator/, tests/Feature/Validator/
  • Dependency: wixel/gump (^v2.3.1)
  • License: GPL-3.0+