einige validierungsfunktionen implementiert für zeit und datums strings. (noch ungetestet/still untested)

This commit is contained in:
Marcel Naeve 2024-05-05 03:45:49 +02:00
parent 0c7df724de
commit b09e3ecd98
Signed by: manae
GPG Key ID: 3BB68BF9EA669981
1 changed files with 97 additions and 0 deletions

View File

@ -202,4 +202,101 @@ class Validate
return preg_match("^([a-zA-Z]){4}([a-zA-Z]){2}([0-9a-zA-Z]){2}([0-9a-zA-Z]{3})?$", $swift); return preg_match("^([a-zA-Z]){4}([a-zA-Z]){2}([0-9a-zA-Z]){2}([0-9a-zA-Z]{3})?$", $swift);
} }
/**
* Static method to validate a Date-String.
* @param string $date Date-String
* @param bool $strict make sure there is only a date, no time?
* @return bool string is a valid date?
*/
static function date(string $date, bool $strict=false) : bool {
$d = strtotime($date);
$reverseDate = date('Y-m-d', $d);
if($d === false) {
return false;
}
if($strict && strtotime($reverseDate) != $d) {
return false;
}
return true;
}
/**
* Static method to validate a String containing a date and a time.
* @param string $datetime DateTime-String
* @param bool $strict make sure if there is both a date and time?
* @return bool string is a valid DateTime?
*/
static function datetime(string $datetime, bool $strict=false) : bool {
$d = strtotime($datetime);
$reverseDate = date('Y-m-d', $d);
if($d === false) {
return false;
}
if($strict && strtotime($reverseDate) != $d) {
return false;
}
return true;
}
/**
* Static method to validate a Time-String.
* @param string $time Time-String
* @return bool string is a valid Time?
*/
static function time(string $time) : bool {
$time = trim($time);
if(preg_match("/^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?$/", $time)) {
$parts = explode(":", $time);
if(count($parts) < 2 or count($parts) > 3) { // at least hours and minutes, seconds optional
return false;
}
$h = intval($parts[0]);
$m = intval($parts[1]);
$s = intval($parts[2]??"0");
if($h === false || $m === false || $s === false) {
return false;
}
if($h < 0 || $m < 0 || $s < 0) {
return false;
}
$fullVal = $h*10000+$m*100+$s;
if($fullVal > 240000) { // max -> 24:00:00 == 00:00:00
return false;
}
if($fullVal < 0) { // min -> 00:00:00
return false;
}
if($h > 24) {
return false;
}
if($m > 59) {
return false;
}
if($s > 59) {
return false;
}
return true;
} elseif (preg_match("/^(0?[1-9]|1[0-2]):[0-5][0-9] (AM|PM)$/i", $time)) {
return true;
}
return false;
}
/**
* Static method for validating date or datetime is in a specific range.
* @param string $value date or datetime to be validated
* @param string $min min value
* @param string $max max value
* @return bool is the value between min and max?
*/
static function datetimeRange(string $value, string $min, string $max) : bool {
$v = strtotime($value);
$l = strtotime($min);
$h = strtotime($max);
if($v === false or $l === false or $h === false) {
return false;
}
return self::range($v, $l, $h);
}
} }