Validate a submitted CSS color

Validate submitted CSS color text without exception-based control flow, then verify the accepted value survives a CSS serialization round trip.

Use this recipe when a form field may contain either a supported concrete CSS color or invalid text. It produces a color object for accepted input and a validation branch for rejected input.

The input must be a concrete color value. Context-dependent CSS such as var() requires a CSS resolution context and is outside this recipe.

Validate the submitted value

Use Color::tryFrom() because invalid text is an expected result at this boundary. Serialize accepted input immediately so the value you store or pass onward is also tested.

use PhpColor\Color\Color;

$inputs = [
    'oklch(0.65 0.18 264)',
    'not-a-color',
];

foreach ($inputs as $input) {
    $color = Color::tryFrom(trim($input));

    if (null === $color) {
        echo $input.' => invalid'.PHP_EOL;
        continue;
    }

    $css = $color->toCss();
    $restored = Color::parse($css);

    assert($restored::getSpaceName() === $color::getSpaceName());
    assert($restored->toCss() === $css);

    echo $input.' => '.$css.PHP_EOL;
}
use PhpColor\Color\Color; $inputs = [ 'oklch(0.65 0.18 264)', 'not-a-color', ]; foreach ($inputs as $input) { $color = Color::tryFrom(trim($input)); if (null === $color) { echo $input.' => invalid'.PHP_EOL; continue; } $css = $color->toCss(); $restored = Color::parse($css); assert($restored::getSpaceName() === $color::getSpaceName()); assert($restored->toCss() === $css); echo $input.' => '.$css.PHP_EOL; }

Verify both validation branches

The fixture prints one canonical CSS value and one rejected value:

oklch(0.65 0.18 264) => oklch(0.65 0.18 264)
not-a-color => invalid
oklch(0.65 0.18 264) => oklch(0.65 0.18 264) not-a-color => invalid

The assertions also reparse the serialized CSS and confirm that this fixture keeps its color space and exact CSS representation.

Adapt the failure branch

Replace the printed invalid result with your form error. Use Color::parse() instead when invalid input is exceptional and the caller needs the parsing error rather than a nullable result.

Related pages