如何使用zend表单比较两个文本字段之间的值


How to compare value among two textfields using zend form?

我有一个包含两个文本字段的表单,即最小金额&最高金额。我想知道是否可以使用Zendform中的验证器将文本字段"最小数量"中的值与文本字段"最大数量

您需要为此创建一个自定义验证。

我认为这篇文章中的功能将帮助您My_Validate_FieldCompare。

只需创建自己的验证器,验证器的isValid方法将获得验证器所附字段的值加上表单的整个上下文,这是所有其他表单字段的值的数组。此外,您可以向验证器添加函数来设置上下文字段,如果它应该更小、相等、更大,甚至传递一个函数来进行比较。。。

这里是一些示例代码(未测试)

<?php
namespace My'Validator;
class MinMaxComp extends AbstractValidator
{
    const ERROR_NOT_SMALLER = 'not_smaller';
    const ERROR_NOT_GREATER = 'not_greater';
    const ERROR_CONFIG = 'wrong_config';
    const TYPE_SMALLER = 0;
    const TYPE_GREATER = 1;
    protected $messageTemplates = array(
        self::ERROR_NOT_SMALLER => "Blah",
        self::ERROR_NOT_GREATER => "Blah",
        self::WRONG_CONFIG => "Blah",
    );
    protected $type;
    protected $contextField;
    public function setType($type)
    {
        $this->type = $type;
    }
    public function setContextField($fieldName)
    {
        $this->contextField = $fieldName;
    }
    public function isValid($value, $context = null)
    {
        $this->setValue($value);
        if (!is_array($context) || !isset($context[$this->contextField])) {
            return false;
        }
        if ($this->type === self::TYPE_SMALLER) {
            if (!$result = ($value < $context[$this->contextField])) {
                $this->error(self::ERROR_NOT_SMALLER);
            }
        } else if ($this->type === self::TYPE_GREATER) {
            if (!$result = ($value > $context[$this->contextField])) {
                $this->error(self::ERROR_NOT_GREATER);
            }
        } else {
            $result = false;
            $this->error(self::ERROR_CONFIG);
        }
        return $result;
    }
}