Validators
Concrete CMS Validation Stack
Validator Concepts
Validator: Implements
\Concrete\Core\Validator\ValidatorInterface
.getRequirementsStrings()
: Lists requirements for validation.isValid($value, array $errors)
: Checks validity; errors added to$errors
.
Translatable Validator: Extends Validator; implements
\Concrete\Core\Validator\TranslatableValidatorInterface
.setRequirementString($code, $message)
: Customizes requirement strings.setErrorString($code, $message)
: Customizes error strings.
Validator For Subject: Extends Validator; implements
\Concrete\Core\Validator\ValidatorForSubjectInterface
.isValidFor($value, $subject = null, array $errors)
: Validates with a subject.
Validator Manager
- Validator Manager: Implements
\Concrete\Core\Validator\ValidatorManagerInterface
. Can nest validators. - Validator Manager For Subject: Extends Validator Manager; for subject validation.
Validator Stack
Term for a ready-to-use validator manager.
Built-in Validators / Stacks
- EmailValidator: Validates emails; configurable MX record check.
- MaximumLengthValidator: Limits maximum length.
- MinimumLengthValidator: Ensures minimum length.
- RegexValidator: Validates against custom regex patterns.
- ReuseValidator (For Subject): Prevents password reuse.
- UniqueUserEmailValidator (For Subject): Checks for unique user emails.
- UniqueUserNameValidator (For Subject): Ensures unique usernames.
Using a Validator Stack
$validator = $app->make('validator/password');
$isValid = $validator->isValid('foo');
// With error messages
$errors = $app->make('error');
if (!$validator->isValid('foo', $errors)) {
// Error output here
}
// With a subject
$user = 1;
if (!$validator->isValidFor('foo', $user, $errors)) {
// Error output here
}
Building a Custom Validator Stack
Example: 10-20 hex characters validator.
$stack = new ValidatorManager();
$maxLength = new MaximumLengthValidator(20);
$minLength = new MinimumLengthValidator(10);
$stack->setValidator('minLength', $minLength);
$stack->setValidator('maxLength', $maxLength);
$onlyHex = new RegexValidator('/^[a-fA-F0-9]+$/');
$onlyHex->setRequirementString($onlyHex::E_DOES_NOT_MATCH, 'Must be hex.');
$onlyHex->setErrorString($onlyHex::E_DOES_NOT_MATCH, 'Invalid hex.');
$stack->setValidator('onlyHex', $onlyHex);
// Using the stack
$errors = $app->make('error');
$isValid = $stack->isValid('Foo', $errors);
// Error output here
Customizing error messages:
$onlyHex = $stack->getValidator('onlyHex');
$onlyHex->setErrorString($onlyHex::E_DOES_NOT_MATCH, function($validator, $error, $value) {
// Custom error message logic here
});
Output:
<p>String "Foo" must be at least 10 characters long.</p>
<p>String "Foo" contains non-hex characters: "o"</p>