简体   繁体   中英

custom validator in InputFilter in Zend Framework 2

I have written a custom class to validate a Dutch BSN (SSN in the US). The code works standalone. However I can not get it to work as validator extending an InputFilter. I did include the class as invokable in 'module.config.php' for my User module.

The code for the class is as follows

<?php

namespace User\Validator;
use Zend\Validator\AbstractValidator;

class CheckBSN extends AbstractValidator {

    //put your code here
    const INVALID = 'BSNInvalid';
    protected $messageTemplates = array(
        self::INVALID => "'%value%' is an invalid BSN",
    ); 

    public function isValid($value) {
        if (!ctype_digit($value)) 
        {
            $this->error(self::INVALID);
            return false;
        }
        if (strlen($value) !== 9) {
            $this->error(self::INVALID);
            return false;
        }

        $pos = 8;
        $checksum = -1 * $value[$pos];
        $weight = 2;

        for ($pos = 7; $pos >= 0; $pos--) {
            $checksum += $weight++ * $value[$pos];
         }

         if (($checksum % 11) !== 0) {
            $this->error(self::INVALID);
            return false;
         }

        return true;
    }
}

I want to add this to the following code in the UserFilter class

$this->add(array(
    'name' => 'bsn',
    'required' => true,
    'filters'  => array(
        array('name' => 'StringTrim'),
        array('name' => 'StripTags'),
    ),
    'validators' => array(
        array('name' => 'StringLength',
            'options' => array(
                'encoding' => 'UTF-8', 
                'min'      => 9, 
                'max'      => 9,
            ),
        ),
    )
));

When I add my class as second validator it is ignored. When I replace the first class , the application crashes with a servicenotfoundexception.

Any help is welcome, I am searching for a solution for days. Yes, I did try the suggestions on this site on none of them appears to apply to my situation

I think you need to use the fully qualified validator class name. Try this code:

$this->add(array(
    'name' => 'bsn',
    'required' => true,
    'filters'  => array(
        array('name' => 'StringTrim'),
        array('name' => 'StripTags'),
    ),
    'validators' => array(
        array('name' => '\User\Validator\CheckBSN',
            'options' => array(                    
            ),
        ),
    )
));

I would also recommend you to look at one of these books for beginners about ZF2. For example, the "Using Zend Framework 2" book which I wrote, has a chapter dedicated to using filters/validators and writing own filters/validators.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM