PHP code example of crtl / validation
1. Go to this page and download the library: Download crtl/validation 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/ */
crtl / validation example snippets
use Crtl\Validation\Custom\Rule as CustomRule;
"ruleName" => ["fieldName1", ..., "fieldNameN"],
"ruleName" => ["fieldName" => "configValue"],
"ruleName" => ["fieldName" => ["config1", "config"]],
CustomRule::class => ["fieldName", ...]
]);
if (!$validator->validate($data)) {
$errors = $validator->getErrors();
}
class UniqueDbColumnRule implements \Crtl\Validation\RuleInterface {
protected $connection;
protected $table;
protected $column;
public function __construct(array $config) {
$this->connection = $config[0] ?? null;
$this->table = $config[0] ?? null;
$this->column = $config[0] ?? null;
}
public function getName() {
return self::class;
}
public function validate($value): bool {
$stmt = $this->db->prepare(
sprintf("SELECT %$2s FROM %$s WHERE %$2s=? LIMIT 1;", $this->table, $this->column)
);
$stmt->bindValue(1, $value);
$stmt->execute();
return $stmt->rowCount() === 0;
}
}
$validator = new Crtl\Validation\Validator([
UniqueDbColumnRule::class => [
"username" => [$db, "users", "username"],
"email" => [$db, "users", "email"]
]
]);
$validator->validate($data);