Skip to content

String Assertions

String assertions validate and check string values for various conditions including length, patterns, and content.

Assert that a string matches a regular expression pattern.

use Cline\Assert\Assertions\Assertion;
Assertion::regex($value, '/^[A-Z][a-z]+$/');
Assertion::regex($code, '/^[A-Z]{3}\d{3}$/', 'Code must be 3 letters followed by 3 digits');

Assert that a string does NOT match a pattern.

Assertion::notRegex($username, '/[^a-zA-Z0-9_]/', 'Username contains invalid characters');

Assert that a string has an exact length.

Assertion::length($zipCode, 5);
Assertion::length($value, 10, null, null, 'utf8');

Assert minimum string length.

Assertion::minLength($password, 8);
Assertion::minLength($username, 3, 'Username must be at least 3 characters');

Assert maximum string length.

Assertion::maxLength($username, 20);
Assertion::maxLength($title, 100, 'Title cannot exceed 100 characters');

Assert string length is within a range.

Assertion::betweenLength($password, 8, 100);
Assertion::betweenLength($name, 2, 50, 'Name must be between 2 and 50 characters');

Assert that a string starts with a substring.

Assertion::startsWith($url, 'https://');
Assertion::startsWith($phoneNumber, '+1', 'Phone number must start with +1');

Assert that a string ends with a substring.

Assertion::endsWith($filename, '.pdf');
Assertion::endsWith($email, '@example.com', 'Email must be from example.com');

Assert that a string contains a substring.

Assertion::contains($content, 'keyword');
Assertion::contains($url, '://secure.', 'URL must contain secure subdomain');

Assert that a string does NOT contain a substring.

Assertion::notContains($password, $username, 'Password cannot contain username');
Assertion::notContains($content, '<script', 'Content cannot contain script tags');

Assert that a string is alphanumeric.

Assertion::alnum($identifier);
Assertion::alnum($code, 'Code must be alphanumeric');
use Cline\Assert\Assert;
Assert::that($password)
->string()
->notEmpty()
->minLength(8)
->maxLength(100)
->notContains($username);
Assert::that($slug)
->string()
->regex('/^[a-z0-9-]+$/')
->minLength(3);
Assert::that($username)
->string()
->betweenLength(3, 20)
->regex('/^[a-zA-Z0-9_]+$/', 'Letters, numbers, and underscores only');
Assert::that($password)
->string()
->minLength(8)
->regex('/[A-Z]/', 'Must contain uppercase letter')
->regex('/[a-z]/', 'Must contain lowercase letter')
->regex('/[0-9]/', 'Must contain number')
->notContains($username, 'Password cannot contain username');
Assert::that($url)
->string()
->notEmpty()
->startsWith('https://')
->url();

String assertions support different character encodings:

Assertion::length($japanese, 5, null, null, 'utf8');
Assertion::minLength($text, 10, null, null, 'ISO-8859-1');