Search code examples
phpzend-framework2zend-validatezend-inputfilter

zf2 inputfilter - how to return a failed custom validation


I am using an input filter with standard ZF2 validators/filters. However i am also extending the \My\InputFilter::isValid method to include domain-specific validation, such as comparing specific parts of dates.

Within this method, how do i signal that validation has failed, with a specific error message for the failed elements? I can return false from within the method but that provides no further information on why the validation failed.

ie:

    public function isValid($context = null){

        $latestCollectionInput = $this->get('latestCollectionTime');
        $requestedCollectionTime = $this->get('requestedCollectionTime');

        $date1 = \DateTime::createFromFormat('d/m/Y H:i', $latestCollectionInput->getRawValue());
        $date2 = \DateTime::createFromFormat('d/m/Y H:i', $requestedCollectionTime->getRawValue());

        if($date1->format('N') !== $date2->format('N')){
            /* how to return failed validation for these elements */            
        }

        return parent::isValid($context);
    }

Solution

  • In the AbstractValidator class there is an error method for this purpose. You can find it here on line 329 on GitHub.

    So when during validation you discover a value is invalid you can do:

    $this->error($key, $value);
    

    Normally the keys are stored in the validator class as constants:

    const ERROR_DATE_NOT_VALID = 'dateNotValid';
    const ERROR_NOT_FUTURE_DATE = 'dateNotFutureDate';
    

    And corresponding messages are stored in a $messageTemplates array:

    protected $messageTemplates = array(
        self::ERROR_DATE_NOT_VALID => "Date must be a string and must be formatted as yyyy-mm-dd",
        self::ERROR_NOT_FUTURE_DATE => "The provided date must be in the future",
    );
    

    When the input filter is collecting error messages on failed validation the key you passed will be used to find the message in the templates list. Those messages will be returned. So when you throw an error using the key like this:

    $this->error(self::ERROR_DATE_NOT_VALID, $value);
    

    The message that will be returned will be:

    "Date must be a string and must be formatted as yyyy-mm-dd"
    

    Read more on writing custom validators here in the official ZF2 docs