marcosh
marcosh

Reputation: 9008

Skip validators in Zend Framework 2 Forms

I am using Zend Framework 2 for building my project. In one of my forms I have a field that needs to be validates with several validators only if a given condition is satisfied (e.g. the value of another form field).

Is there a way to skip completely the validation of a field based on an external condition?

Upvotes: 0

Views: 534

Answers (2)

AlexP
AlexP

Reputation: 9857

You can also use the $context argument from Zend\Validator\ValidatorInterface to grab the value of the other form element. All you would need is a custom validator and set it on the form element.

For example:

use Zend\Validator;
use Zend\Validator\Exception;

class MyCustomValidator implements Validator\ValidatorInterface
{
    public function isValid($value, array $context = [])
    {
        if (! isset($context['name_of_other_field'])) {
            throw new Exception\RuntimeException('name_of_other_field missing.');
        }

        if (1234 === $context['name_of_other_field']) {

            $validator = new Validator\ValidatorChain();

            $validator->attach(new Validator\StringLength(['min' => 8, 'max' => 12]));
            $validator->attach(new Validator\EmailAddress());

            return $validator->isValid($value);
        }

        return true;
    }

    public function getMessages()
    {}
} 

Upvotes: 0

Wilt
Wilt

Reputation: 44336

You can use the method setValidationGroup inside the InputFilter class to set what input fields should be validated.

You could for example extend the InputFilter class and use the setValidationGroup in a customized setData method, and set the group depending on the presence of a certain field in $data.

For example something like this:

<?php

namespace Application\InputFilter;

use Zend\InputFilter\InputFilter;

class CustomInputFilter extends InputFilter
{
    /**
     * Set data to use when validating and filtering
     *
     * @param  array|Traversable $data
     * @return InputFilterInterface
     */
    public function setData($data)
    {
        $group = array(
            // your custom validation group
        );
        if(isset($data['fieldName'])){
            $this->setValidationGroup($group);
        }

        // Forward to default setData method
        return parent::setData($data);
    }
}

Extending the class is just one option to show what is possible. You can of course also setValidationGroup somewhere else externally without a customizing the InputFilter class.

$group = array(
    // your custom validation group
);
$inputFilter->setValidationGroup($group);

Upvotes: 1

Related Questions