A date validator that checks if a date is greater than or equal to today's value using the Zend Framework

$form = new Zend_Form();

$mockDate = new Zend_Form_Element_Text('mock');

$mockDate->addValidator(???????);

$form->addElements(array($mockDate));

$result = $form->isValid();

if ($result) echo "YES!!!";
else echo "NO!!!";

Suppose the item is in a date format. How to determine that the specified date is greater than or equal to today?

+3
source share
3 answers

To do this, you can create a simple validator:

class My_Validate_DateGreaterThanToday extends Zend_Validate_Abstract
{
    const DATE_INVALID = 'dateInvalid';

    protected $_messageTemplates = array(
        self::DATE_INVALID => "'%value%' is not greater than or equal today"
    );

    public function isValid($value)
    {
        $this->_setValue($value);

        $today = date('Y-m-d');

        // expecting $value to be YYYY-MM-DD
        if ($value < $today) {
            $this->_error(self::DATE_INVALID);
            return false;
        }

        return true;
    }
}

And add it to the element:

$mockDate->addValidator(new My_Validate_DateGreaterThanToday());

You probably want to check the date using Zend_Datedate localization and additional benefits.

To create custom validations, check out the writing of validators from the Zend manual.

+6
source
. ZF2 . / :
public function getInputFilter()
{
    if(!$this->inputFilter){
        $inputFilter = new InputFilter();
        $inputFilter->add(array(
            'name' => 'mock',
            'validators' => array(
                array('name' => 'Date'),
                array(
                    'name' => 'GreaterThan',
                    'options' => array(
                        'min' => date('Y-m-d'),
                    ),
                ),
            ),
        ));
        $this->inputFilter = $inputFilter;
    }
    return $this->inputFilter;
}

. "", , ​​ "true" ( "" GreaterThan), ""

+1
class My_Validate_DateGreaterThanToday extends Zend_Validate_Abstract
{
    const DATE_INVALID = 'dateInvalid';

    protected $_messageTemplates = array(
        self::DATE_INVALID => "'%value%' is not greater than today"
    );

    public function isValid($value) {
        $this->_setValue($value);

        $date = new Zend_Date($value);
        $date->addDay(1);
        $now = new Zend_Date();

        // expecting $value to be YYYY-MM-DD
        if ($now->isLater($date)) {
            $this->_error(self::DATE_INVALID);
            return false;
        }

        return true;
    }
}

, Zend_Date , awsner - , ...

0

Source: https://habr.com/ru/post/1732096/


All Articles