Validation

Validation checks whether supplied values meet your application's rules. Use a fluent schema when the values are already in an array or the rules depend on other fields. Use PHP attributes when the rules belong to a class. Both APIs return a result with errors grouped by field.

The examples use the same two rulesets: a required subject of at most 80 characters, and a required priority of normal or urgent.

Fluent Schema

Build a schema with Schema::make(). Call field() to select the key you want to validate and chain its rules. Call schema() on the field builder to get the schema back when you finish.

use Atom\Validation\Schema;

$schema = Schema::make()
    ->field("subject")
        ->required("Enter a subject.")
        ->maxLength(80, "Use 80 characters or fewer.")
        ->schema()
    ->field("priority")
        ->required("Choose a priority.")
        ->in(["normal", "urgent"], "Choose normal or urgent.")
        ->schema();

$result = $schema->validate(["subject" => "", "priority" => "high"]);

Add a rule conditionally

You can add rules before running the schema. Here an email address is optional for a normal request and required for an urgent one. The email() rule checks the format when an address is supplied.

$fields = ["subject" => "Printer offline", "priority" => "urgent"];
$replyEmail = $schema->field("reply_email")
    ->email("Enter a valid reply address.");

if ($fields["priority"] === "urgent") {
    $replyEmail->required("Add a reply address for urgent requests.");
}

$result = $schema->validate($fields);

Attribute Validation

Declare the same subject and priority rules on an object when several callers share those rules. Pass an instance to Validator::for()->validate().

use Atom\Validation\Rules\In;
use Atom\Validation\Rules\MaxLength;
use Atom\Validation\Rules\Required;
use Atom\Validation\Validator;

final class TicketInput
{
    #[Required("Enter a subject.")]
    #[MaxLength(80, "Use 80 characters or fewer.")]
    public string $subject = "";

    #[Required("Choose a priority.")]
    #[In(["normal", "urgent"], "Choose normal or urgent.")]
    public string $priority = "";
}

$input = new TicketInput();
$input->priority = "high";
$result = Validator::for()->validate($input);

Read validation errors

Use failed() or passed() to decide whether to continue. messages() returns all messages grouped by field. Use first() when the UI needs one message for a specific field.

if ($result->failed()) {
    $errors = $result->messages();
    $subjectError = $result->first("subject");
}

For the invalid subject and priority in the first and third snippets, messages() returns:

[
    "subject" => ["Enter a subject."],
    "priority" => ["Choose normal or urgent."],
]

See Hydration for how Atom populates an input object from request data before validation.