0

我有一个带有 2 个文本字段的表单,即最小金额和最大金额。我想知道我是否可以使用 Zendform 中的验证器将文本字段“最小数量”中的值与文本字段“最大数量”中的值进行比较,反之亦然。

4

2 回答 2

3

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

我认为这篇文章中的函数会帮助你My_Validate_FieldCompare

于 2013-02-21T07:35:26.493 回答
1

只需创建自己的验证器,验证器的 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;
    }
}
于 2013-02-21T07:35:42.070 回答