You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
73 lines
2.5 KiB
73 lines
2.5 KiB
<?php
|
|
|
|
namespace IQBall\Core\Validation;
|
|
|
|
/**
|
|
* A collection of standard validators
|
|
*/
|
|
class Validators {
|
|
/**
|
|
* @return Validator a validator that validates a given regex
|
|
*/
|
|
public static function regex(string $regex, ?string $msg = null): Validator {
|
|
return new SimpleFunctionValidator(
|
|
fn(string $str) => preg_match($regex, $str),
|
|
fn(string $name) => [new FieldValidationFail($name, $msg == null ? "field does not validates pattern $regex" : $msg)]
|
|
);
|
|
}
|
|
|
|
/**
|
|
* @return Validator a validator that validates strings that only contains numbers, letters, accents letters, `-` and `_`.
|
|
*/
|
|
public static function name(?string $msg = null): Validator {
|
|
return self::regex("/^[0-9a-zA-Zà-üÀ-Ü_-]*$/", $msg);
|
|
}
|
|
|
|
/**
|
|
* @return Validator a validator that validates strings that only contains numbers, letters, accents letters, `-`, `_` and spaces.
|
|
*/
|
|
public static function nameWithSpaces(): Validator {
|
|
return self::regex("/^[0-9a-zA-Zà-üÀ-Ü _-]*$/");
|
|
}
|
|
|
|
/**
|
|
* Validate string if its length is between given range
|
|
* @param int $min minimum accepted length, inclusive
|
|
* @param int $max maximum accepted length, exclusive
|
|
* @return Validator
|
|
*/
|
|
public static function lenBetween(int $min, int $max): Validator {
|
|
return new FunctionValidator(
|
|
function (string $fieldName, string $str) use ($min, $max) {
|
|
$len = strlen($str);
|
|
if ($len >= $max) {
|
|
return [new FieldValidationFail($fieldName, "trop long, maximum $max caractères.")];
|
|
}
|
|
if ($len < $min) {
|
|
return [new FieldValidationFail($fieldName, "trop court, minimum $min caractères.")];
|
|
}
|
|
return [];
|
|
}
|
|
);
|
|
}
|
|
|
|
|
|
public static function isInteger(): Validator {
|
|
return self::regex("/^[0-9]+$/");
|
|
}
|
|
|
|
public static function isIntInRange(int $min, int $max): Validator {
|
|
return new SimpleFunctionValidator(
|
|
fn(string $val) => intval($val) >= $min && intval($val) <= $max,
|
|
fn(string $name) => [new FieldValidationFail($name, "The value is not in the range $min to $max ")]
|
|
);
|
|
}
|
|
|
|
public static function isURL(): Validator {
|
|
return new SimpleFunctionValidator(
|
|
fn($val) => filter_var($val, FILTER_VALIDATE_URL),
|
|
fn(string $name) => [new FieldValidationFail($name, "The value is not an URL")]
|
|
);
|
|
}
|
|
}
|