Search code examples
phpvalidationzend-framework2

Zend Framework 2 Custom Validators for Forms


I'm trying to make a user registration form which checks for the complexity of the password field. I've written a custom validator to do this according to the documentation. This file lives in my 'User' module at User\src\User\Validator.

<?php

namespace User\Validator;

use Zend\Validator\AbstractValidator;

class PasswordStrength extends AbstractValidator {

const LENGTH = 'length';
const UPPER  = 'upper';
const LOWER  = 'lower';
const DIGIT  = 'digit';

protected $messageTemplates = array(
    self::LENGTH => "'%value%' must be at least 6 characters long",
    self::UPPER => "'%value% must contain at least one uppercase letter",
    self::LOWER => "'%value% must contain at least one lowercase letter",
    self::DIGIT => "'%value% must contain at least one digit letter"
);

public function isValid($value) {
    ... validation code ...
}
}

My problem arises in trying to use this validator in my user registration form. I tried adding the validator to the ServiceManager by configuring it in Module.php.

public function getServiceConfig() {
    return array(
        'invokables' => array(
            'PasswordStrengthValidator' => 'User\Validator\PasswordStrength'
        ),
    );
}

Then I added it to the input filter in User.php.

public function getInputFilter() {
    if (!$this->inputFilter) {
        $inputFilter = new InputFilter();
        $factory     = new InputFactory();

        $inputFilter->add($factory->createInput(array(
            'name'     => 'username',
            'required' => true,
            'validators' => array(
                array(
                    'name'    => 'StringLength',
                    'options' => array(
                        'encoding' => 'UTF-8',
                        'min'      => 1,
                        'max'      => 100,
                    ),
                ),
            ),
        )));

        $inputFilter->add($factory->createInput(array(
            'name'     => 'password',
            'required' => true,
            'validators' => array(
                array(
                    'name'    => 'PasswordStrengthValidator',
                ),
            ),
        )));

        $this->inputFilter = $inputFilter;
    }

    return $this->inputFilter;
}

However, when I access the form and hit the submit button, I get a ServiceNotFoundException.

Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for PasswordStrengthValidator

Is there a problem with my ServiceManager configuration? I'm not even sure if this is the appropriate way to use a custom validator in the first place. I've found plenty of examples using ZF1, but the documentation and examples for ZF2 that I've found never extend beyond the writing of the validator to address its integration with forms, etc. Any advice would be greatly appreciated.


Solution

  • The "short name" validator loading you are attempting to use in your example only works if you register that short name / alias with the validator plugin manager (Zend\Validator\ValidatorPluginManager) first.

    One alternative to this (and the way I do it) is to inject instances of necessary custom validators when creating the form filter object. This is the way ZfcUser does it:

    // Service factory definition from Module::getServiceConfig
    'zfcuser_register_form' => function ($sm) {
         $options = $sm->get('zfcuser_module_options');
         $form = new Form\Register(null, $options);
         $form->setInputFilter(new Form\RegisterFilter(
             new Validator\NoRecordExists(array(
                 'mapper' => $sm->get('zfcuser_user_mapper'),
                 'key'    => 'email'
             )),
             new Validator\NoRecordExists(array(
                'mapper' => $sm->get('zfcuser_user_mapper'),
                'key'    => 'username'
             )),
             $options
         ));
         return $form;
    },
    

    Source: https://github.com/ZF-Commons/ZfcUser/blob/master/Module.php#L100

    Here, the two ZfcUser\Validator\NoRecordExists validator instances (one for email and one for username) are injected into the constructor of the input filter object for the registration form (ZfcUser\Form\RegisterFilter).

    Then, inside the ZfcUser\Form\RegisterFilter class, the validators are added to the element definitions:

    $this->add(array(
        'name'       => 'email',
        'required'   => true,
        'validators' => array(
            array(
                'name' => 'EmailAddress'
            ),
            // Constructor argument containing instance of the validator
            $emailValidator
        ),
    ));
    

    Source: https://github.com/ZF-Commons/ZfcUser/blob/master/src/ZfcUser/Form/RegisterFilter.php#L37

    I believe another alternative is to use the fully-qualified class name as the validator name (ie: "User\Validator\PasswordStrength" instead of just "PasswordStrengthValidator"), though i've never attempted this myself.