Validate color input

Use a nullable result for expected invalid text and an exception when malformed input breaks a trusted contract.

#3b82f6accepted
oklch(0.65 0.18 264)accepted
not-a-colorrejected

Separate accepted colors from rejected text

A nullable parser turns a mixed input queue into concrete objects or an explicit invalid branch. Accepted values can immediately carry a normalized representation.

Use null when invalid input is expected

Color::tryFrom() keeps a form or import branch explicit. Use the throwing parser only when malformed input breaks a trusted contract and the error detail matters.

<?php

use PhpColor\Color\Color;

$submittedValue = 'oklch(0.65 0.18 264)';
$color = Color::tryFrom($submittedValue);

if (null === $color) {
    return 'Choose a supported color value.';
}

echo $color->toCss();
use PhpColor\Color\Color; $submittedValue = 'oklch(0.65 0.18 264)'; $color = Color::tryFrom($submittedValue); if (null === $color) { return 'Choose a supported color value.'; } echo $color->toCss();

Pass one typed result into the rest of the application

Successful input becomes a ColorInterface, whether the boundary received a string or an existing color object. Downstream code no longer needs to branch on the submitted notation.

Result
OklchColor
Space
oklch
Alpha
0.5

Keep syntax validation separate from product rules

A parsed value only proves that PHPColor recognizes the syntax. It does not prove that the color fits a target gamut, meets a contrast threshold, or belongs in an application's allowed palette.

SyntaxCan PHPColor parse this concrete value?
GamutDoes the result fit the selected target space?
ContrastDoes the final color pair meet its criterion?
PolicyDoes the application allow this value?

Continue

Apply validation at a real input boundary