0 follower

Final Class Yiisoft\Validator\Rule\RequiredHandler

InheritanceYiisoft\Validator\Rule\RequiredHandler
ImplementsYiisoft\Validator\RuleHandlerInterface

A handler for {@see Required} rule. Validates that the specified value is passed and is not empty.

Method Details

Hide inherited methods

__construct() public method

public mixed __construct ( callable|null $defaultEmptyCondition null )
$defaultEmptyCondition callable|null

A default empty condition used to determine emptiness of the value.

                public function __construct(
    ?callable $defaultEmptyCondition = null,
) {
    $this->defaultEmptyCondition = $defaultEmptyCondition ?? new WhenEmpty(trimString: true);
}

            
validate() public method

public Yiisoft\Validator\Result validate ( mixed $value, Yiisoft\Validator\RuleInterface $rule, Yiisoft\Validator\ValidationContext $context )
$value mixed
$rule Yiisoft\Validator\RuleInterface
$context Yiisoft\Validator\ValidationContext

                public function validate(mixed $value, RuleInterface $rule, ValidationContext $context): Result
{
    if (!$rule instanceof Required) {
        throw new UnexpectedRuleException(Required::class, $rule);
    }
    $result = new Result();
    if ($context->isPropertyMissing()) {
        $result->addError($rule->getNotPassedMessage(), [
            'property' => $context->getTranslatedProperty(),
            'Property' => $context->getCapitalizedTranslatedProperty(),
        ]);
        return $result;
    }
    $emptyCondition = $rule->getEmptyCondition() ?? $this->defaultEmptyCondition;
    if (!$emptyCondition($value, $context->isPropertyMissing())) {
        return $result;
    }
    $result->addError($rule->getMessage(), [
        'property' => $context->getTranslatedProperty(),
        'Property' => $context->getCapitalizedTranslatedProperty(),
    ]);
    return $result;
}