PHP code example of changhorizon / validation-interface
1. Go to this page and download the library: Download changhorizon/validation-interface library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
changhorizon / validation-interface example snippets
use ChangHorizon\ValidationInterface\Result\ValidationResult;
use ChangHorizon\ValidationInterface\Validator\AbstractValidator;
class EmailValidator extends AbstractValidator
{
public function validate(): ValidationResult
{
if (!is_string($this->target) || !filter_var($this->target, FILTER_VALIDATE_EMAIL)) {
return $this->fail('Invalid email address', 'INVALID_EMAIL');
}
return $this->ok();
}
}
$email = '[email protected]';
$validator = new EmailValidator($email); // 目标对象通过构造传入
$result = $validator->validate();
if ($result->isValid()) {
echo "Email is valid.";
} else {
echo "Validation failed: " . $result->getError();
}
namespace ChangHorizon\ValidationInterface\Validator;
use ChangHorizon\ValidationInterface\Result\ValidationResult;
use ChangHorizon\ValidationInterface\ValidatorInterface;
abstract class AbstractValidator implements ValidatorInterface
{
protected object $target;
public function __construct(object $target)
{
$this->target = $target;
}
abstract public function validate(): ValidationResult;
protected function ok(): ValidationResult
{
return ValidationResult::ok();
}
protected function fail(string $error, ?string $code = null): ValidationResult
{
return ValidationResult::fail($error, $code);
}
}