Zend框架1:两个相关字段的表单验证


Zend framework 1: form validation of two related fields

我的ZF1表单有相互关联的fieldland和fieldnumber,我需要检查是否同时填写或不填写。如何进行此验证?在ZF1中,表单没有方法setValidatorGroup。那么,还有其他选择吗?

表单是在xml中定义的,因此字段定义看起来像:

    <klant_mobiel_land>
        <type>text</type>
        <options>
            <label>Mobiel landcode, abonneenummer:</label>
            <maxlength>5</maxlength>
            <size>5</size>
            <validators>
                <telefoonnummerlandcodecinco>
                   <validator>TelefoonnummerLandcodeCinco</validator>
                </telefoonnummerlandcodecinco>
            </validators>
        </options>
    </klant_mobiel_land>
    <klant_mobiel_nummer>
        <type>text</type>
        <options>
            <maxlength>10</maxlength>
            <size>15</size>
        </options>
    </klant_mobiel_nummer>

我希望需要一个验证组,首先,这是选项吗?其次,应该如何在xml中定义它?也许是这样的:

  <validationgroups>
        <mobilephone_group>
            <elements>
                <klant_mobiel_nr>klant_mobiel_nummer</klant_mobiel_nr>
                <klant_mobiel_land>klant_mobiel_land</klant_mobiel_land>
            </elements>
            <validators>
                <neitherorbothfields>
                    <validator>neitherorbothfields</validator>
                </neitherorbothfields>
            </validators>
        </mobilephone_group>
    </validationgroups>

以及验证器本身,它应该如何将这两个值传递给它?也许是这样的:

class Zend_Validate_NeitherOrBothFields extends Zend_Validate_Abstract
{
     public function isValid($value, $context = null)
    {
        if (mytestToSeeIfNeitherOrBothAreFilled) {
            $this->_error('Only one of the two fields has been filled, fill either none or both', $value);
            return false;
        };
        return true;
    }

尊敬的Tim van Steenbergen,tieka.nl

通常,验证器使用可选的$context var,正如您上面指出的那样。但是,您将把验证器附加到一个字段(因此,任何验证失败也将附加到该字段)。

标准示例是请求password值和confirm_password值的注册表。验证器可以附加到password字段,验证器的isValid($value, $context = null)方法将比较$value$context['confirm_password']。失败会在password字段上设置一个错误,然后在视图脚本或表单装饰器中引用该字段。

您可以拥有自定义验证器,并使用isValid可用的第二个参数来拥有其他post字段,如下所示:

class Zend_Validate_NeitherOrBothFields  extends Zend_Validate_Abstract
{
    public function isValid($value, $context = NULL) {
       // in $context you will have all data from post which you can use to validate and do the stuffs you want and the end you can set the error message and return true/false
        if ($context['password'] !== $context['confirm_password']) {
            $this->_error('some message');
            return false; 
        }
        return true;
    }
}

然后在你的Zend表单中,只需将这个验证器绑定到你的一个字段(比如说只绑定到密码)