我正在尋找一種方法來驗證通過表單獲得的一個陣列。
$arr = [13, 64];
該陣列由 2 個整陣列成,我需要檢查這些整數是否介于 0 到 1000 之間,但第二個整數也大于第一個整數,并且差值不能超過 100。我唯一能設定的約束是驗證具有已知模式的數字:
'constraints' => new Assert\Collection([
'fields' => [
0 => new Assert\Range([
'min' => 0,
'max' => 1000,
]),
1 => new Assert\Range([
'min' => 0,
'max' => 1000,
]),
]
]),
我的驗證中缺少什么:
$arr = [13, 64]; => should be correct
$arr = [140, 64]; => not correct, $arr[0] > $arr[1]
$arr = [13, 340]; => not correct, ($arr[1] - $arr[0]) > 100
我無法在 symfony 檔案中找到如何驗證彼此之間的陣列欄位,并且不知道是否有辦法。
如果有人有小費,歡迎您:)
謝謝你,干杯!
uj5u.com熱心網友回復:
創建自定義表單約束。
創建2個檔案并將它們放入src/Validator
約束:
// src/Validator/CheckArray.php
namespace App\Validator;
use Symfony\Component\Validator\Constraint;
class CheckArray extends Constraint
{
public $type = 'One of the values is not an integer.';
public $range = 'One of the values is not within range. (0 and 1000)';
public $exceeded = 'Value mismatched. Exceeded expected value.';
}
驗證者:
// src/Validator/CheckArrayValidator.php
namespace App\Validator;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;
class CheckArrayValidator extends ConstraintValidator
{
public function validate($array, Constraint $constraint)
{
if (!$constraint instanceof CheckArray) {
throw new UnexpectedTypeException($constraint, CheckArray::class);
}
if (null === $array || '' === $array) {
return;
}
if (!is_array($array)) {
throw new UnexpectedValueException($array, 'array');
}
if ($this->checkType()) {
$this->context->buildViolation($constraint->type)->addViolation();
}
if ($this->checkRange()) {
$this->context->buildViolation($constraint->range)->addViolation();
}
if ($this->checkExceeded()) {
$this->context->buildViolation($constraint->exceeded)->addViolation();
}
}
private function checkType(array $array): bool
{
return $array !== array_filter($array, 'is_int');
}
private function checkRange(array $array): bool
{
return $array !== array_filter($array, function($v){
return ($v > 0 && $v < 1000);
});
}
private function checkExceeded(array $array): bool
{
if ($array[0] > $array[1]) return true;
if (($array[1] - $array[0]) > 100) return true;
return false;
}
}
在您的表格中:
use App\Validator\CheckArray;
'constraints' => new CheckArray()
未經過全面測驗,根據需要調整命名和訊息或添加更多內容。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/488268.html
