Checkout date in zendframework2

Hiho, I would like to validate a date field from the zf2 form. I've set the "format" parameter to get the format I want. But every time I check it I get an error. The validator looks like this:

            $inputFilter->add($factory->createInput(array(
            'name' => 'user_data_birth',
            'required' => false,
            'validators' => array(
                array(
                'name' => 'Date',
                'options' => array(
                    'format' => 'd.m.Y',
                    'locale' => 'de',
                    'messages' => array(
                        \Zend\Validator\Date::INVALID => 'Das scheint kein gültiges Datum zu sein.',
                        \Zend\Validator\Date::INVALID_DATE => 'Das scheint kein gültiges Datum zu sein. (Invalid Date)',
                        \Zend\Validator\Date::FALSEFORMAT => 'Das Datum ist nicht im richtigen Format.',
                        ),
                    ),
                ),
                array(
                    'name' => 'NotEmpty',
                    'options' => array(
                    'messages' => array(
                        \Zend\Validator\NotEmpty::IS_EMPTY => 'Bitte geben Sie das Datum an'
                        ),
                    ),
                )
            ),
        )));

      

But I get an error every time when the date is in the wrong format.

+3


source to share


4 answers


You can solve the problem, the start date must be less than the check for the end date using a callback function as shown below:

          $inputFilter->add($factory->createInput(array(
                'name' => 'end_date',
                'required' => true,                 
                'filters' => array(
                        array('name' => 'StripTags'),
                        array('name' => 'StringTrim'),
                ),
                'validators' => array(
                    array(
                        'name' => 'Callback',
                        'options' => array(
                            'messages' => array(
                                    \Zend\Validator\Callback::INVALID_VALUE => 'The end date should be greater than start date',
                            ),
                            'callback' => function($value, $context = array()) {                                    
                                $startDate = \DateTime::createFromFormat('d-m-Y', $context['start_date']);
                                $endDate = \DateTime::createFromFormat('d-m-Y', $value);
                                return $endDate >= $startDate;
                            },
                        ),
                    ),                          
                ),
        )));

      



Using the above code I solved my problem. Hope this helps.

+13


source


you need to change the validator that is in the date element. If you pass the format to the element, you will be fine. You can also take a validator from an element.

$date = new Element\DateTime('test');
$date->setFormat('d.m.Y');

      



or

$validators = $date->getValidators()
// apply you changes

      

+1


source


Have you tried another format, for example the basic one: "Ymd"? What's the result?

0


source


The CallBack function is a very convenient way if we only need to use it in one form. In most cases, we will need to use this in multiple places. I did some research and wrote this custom validator. This validator compares two strings; I added another trick to find out if these lines are different or the same.

If we change the password; then the old password and new password will be different at the same time, we need a new password check to be the same as the new password. This validator can be used for both cases, simply by changing the "true" or "false" parameter.

Form Fields
user_password
new_user_password
new_user_password_verify

      

create a new StringCompare.php validator in application \ src \ Application \ Validator

<?php

namespace Application\Validator;

class StringCompare extends \Zend\Validator\AbstractValidator {

    const SAME = 'same';
    const DIFFERENT = 'different';

    protected $messageTemplates = array(
        self::SAME => "Both the words are the same",
        self::DIFFERENT => "Both the words are different",
    );

    protected $messageVariables = array(
        'compareWith' => array( 'options' => 'compareWith' ),
        'different' => array( 'options' => 'different' ),
    );

    protected $options = array(
        'compareWith' => "",
        'different' => true,
        'encoding' => 'UTF-8',
    );

    public function __construct( $options = array( ) ) {
        parent::__construct( $options );
    }

    public function getCompareWith( ) {
        return $this->options[ 'compareWith' ];
    }

    public function getDifferent( ) {
        return $this->options[ 'different' ];
    }

    public function isValid( $value, $context=array( ) ) {

        $compareWith = $this->getCompareWith( );
        $different = $this->getDifferent( );

        $returnValue =  $value == $context[$compareWith];
        if ( $different ) {
            $returnValue = !$returnValue;
       if ( !$returnValue ) {
          $this->error( self::SAME );
           }
        } else {
        if ( !$returnValue ) {
        $this->error( self::DIFFERENT );
        }
    }
        return $returnValue;


    }

}

      

Add the following to your form filter:

$this->add ( array (
    'name'  => 'new_user_password',
    'required' => true,
    'filters' => array (
        array ( 
            'name' => 'StringTrim',
        ),
    ),
    'validators' => array (
        array (
            'name' => 'StringLength',
            'options' => array (
                'min' => 8,
                'max' => 20,
            )
        ),
        array (
            'name' => 'Application\Validator\StringCompare',
            'options' => array (
                'compareWith' => 'user_password',
                'different' => true,
            ),
        ),
    )
) );

      

Perform form validation in the controller and we're done. If we use different = 'true', the validation procedure ensures that the two values ​​differ from each other, if we use “false”, then this ensures that the strings are the same.

0


source







All Articles