dragon-forks/kernel/helpers/validators.php
2025-07-17 20:31:05 +02:00

72 lines
No EOL
1.9 KiB
PHP

<?php
class Validator {
private static function getValue($array, $keys) {
$key = $keys[0];
return $array[$key];
}
private static function getValues($array, $keys) {
$list = [];
foreach ($keys as $key) {
$list[] = $array[$key];
}
return $list;
}
public function required($name, $array, $keys) {
$value = Validator::getValue($array, $keys);
if ($value == "" || $value == null || trim($value) == "") {
return "{$name} field is required";
}
return null;
}
public function mail($name, $array, $keys) {
$value = Validator::getValue($array, $keys);
if (!is_email($value)) {
return "{$name} field must be valid";
}
return null;
}
public function equals($name, $array, $keys) {
$values = Validator::getValues($array, $keys);
$match = true;
$firstValue = $values[0];
foreach ($values as $value) {
if ($value !== $firstValue) {
$match = false;
}
}
if (!$match) {
return "{$name} fields must match";
}
return null;
}
public function alphanumeric($name, $array, $keys) {
$value = Validator::getValue($array, $keys);
if (preg_match("/[^A-z0-9_\-]/", $value)==1) { // Thanks to "Carlos Pires" from php.net!
return "{$name} fields must be alphanumeric";
}
return null;
}
public function unique($name, $array, $keys, $database) {
global $db;
$value = Validator::getValue($array, $keys);
$table = $database["table"];
$dbField = $database["field"];
if ($db->checkUnique($table, $dbField, $value)) {
return "{$value} already taken, it must be unique";
}
return null;
}
}