respect-validation/tests/feature/Validators/TrimmedTest.php
Alexandre Gomes Gaigalas 618b2a3661
Introduce Trimmed validator
This commit introduces the `Trimmed` validator that ensures a string
cannot start or end with a list of specific values.

The default values used are a selected list of Unicode invisible
characters.

To support this change, the StartsWith and EndsWith validators were
modified so they can also support multiple values to check for.

While StartsWith and EndsWith are more generic, and also perform
start-of-array and end-of-array kinds of checks, Trimmed is more
focused on string inputs, which tailors to a more specific use
case.
2026-02-26 03:29:30 -03:00

35 lines
1.5 KiB
PHP

<?php
/*
* SPDX-License-Identifier: MIT
* SPDX-FileCopyrightText: (c) Respect Project Contributors
* SPDX-FileContributor: Alexandre Gomes Gaigalas <alganet@gmail.com>
*/
declare(strict_types=1);
test('default template', catchAll(
fn() => v::trimmed()->assert(' word'),
fn(string $message, string $fullMessage, array $messages) => expect()
->and($message)->toBe('" word" must not contain leading or trailing whitespace')
->and($fullMessage)->toBe('- " word" must not contain leading or trailing whitespace')
->and($messages)->toBe(['trimmed' => '" word" must not contain leading or trailing whitespace']),
));
test('inverted template', catchAll(
fn() => v::not(v::trimmed())->assert('word'),
fn(string $message, string $fullMessage, array $messages) => expect()
->and($message)->toBe('"word" must contain leading or trailing whitespace')
->and($fullMessage)->toBe('- "word" must contain leading or trailing whitespace')
->and($messages)->toBe(['notTrimmed' => '"word" must contain leading or trailing whitespace']),
));
test('custom alternatives', catchMessage(
fn() => v::trimmed('foo', 'bar')->assert('foobaz'),
fn(string $message) => expect($message)->toBe('"foobaz" must not contain leading or trailing "foo" or "bar"'),
));
test('custom alternatives inverted template', catchMessage(
fn() => v::not(v::trimmed('foo', 'bar'))->assert('bazqux'),
fn(string $message) => expect($message)->toBe('"bazqux" must contain leading or trailing "foo" or "bar"'),
));