Back to Validation

UndefOr

docs/validators/UndefOr.md

3.1.12.3 KB
Original Source
<!-- SPDX-License-Identifier: MIT SPDX-FileCopyrightText: (c) Respect Project Contributors SPDX-FileContributor: Alexandre Gomes Gaigalas <[email protected]> SPDX-FileContributor: Henrique Moody <[email protected]> -->

UndefOr

  • UndefOr(Validator $validator)

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

This validator can be particularly useful when validating form fields.

Usage

php
v::undefOr(v::alpha())->assert('');
// Validation passes successfully

v::undefOr(v::digit())->assert(null);
// Validation passes successfully

v::undefOr(v::alpha())->assert('username');
// Validation passes successfully

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

Prefix

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

php
v::undefOrEmail()->assert('not an email');
// → "not an email" must be an email address or must be undefined

v::undefOrBetween(1, 3)->assert(2);
// Validation passes successfully

Templates

UndefOr::TEMPLATE_STANDARD

ModeTemplate
defaultor must be undefined
invertedand must not be undefined

Template as suffix

The template serves as a suffix to the template of the inner validator.

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

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

Template placeholders

PlaceholderDescription
subjectThe validated input or the custom validator name (if specified).

Categorization

  • Nesting

Changelog

VersionDescription
3.0.0Templates changed
3.0.0Renamed to UndefOr
1.0.0Created as Optional

See Also