respect-validation/docs/rules/UndefOr.md
Henrique Moody 562d98d805
Refactor the NotEmpty rule
Since we have the ability to use `not` as a prefix, having rules that
validate negative behaviour makes them a bit inflexible, verbose, and
harder to understand.

This commit will refactor the `NotEmpty`, and rename it to `Falsy`. It
will no longer trim strings, because Blank does a much better job at it;
it only simulates the behaviour of PHP’s native `empty()` function.

Because `Falsy`, `Blank`, and `Undef` have similar behaviour, I created
a page to demonstrate the difference and show when the user should use
one or the other.

Assisted-by: Cursor (claude-4.5-opus-high)
2025-12-29 12:48:35 +01:00

1.7 KiB

UndefOr

  • UndefOr(Rule $rule)

Validates the input using a defined rule when the input is not null or an empty string ('').

This rule can be particularly useful when validating form fields.

Usage

v::undefOr(v::alpha())->isValid(''); // true
v::undefOr(v::digit())->isValid(null); // true

v::undefOr(v::alpha())->isValid('username'); // true
v::undefOr(v::alpha())->isValid('has1number'); // false

Prefix

For convenience, you can use the undefOr as a prefix to any rule:

v::undefOrEmail()->isValid('not an email'); // false
v::undefOrBetween(1, 3)->isValid(2); // true

Templates

UndefOr::TEMPLATE_STANDARD

Mode Template
default or must be undefined
inverted and must not be undefined

The templates from this rule serve as message suffixes:

v::undefOr(v::alpha())->assert('has1number');
// "has1number" must contain only letters (a-z) or must be undefined

v::not(v::undefOr(v::alpha()))->assert("alpha");
// "alpha" must not contain letters (a-z) and must not be undefined

Template placeholders

Placeholder Description
subject The validated input or the custom validator name (if specified).

Categorization

  • Nesting

Changelog

Version Description
3.0.0 Renamed to UndefOr
1.0.0 Created as Optional

See also: