簡體   English   中英

Zend框架1:兩個相關領域的表單驗證

[英]Zend framework 1: form validation of two related fields

我的ZF1表格具有彼此相關的fieldland和fieldnumber,我需要檢查兩者是否都填寫。 如何進行驗證? 在ZF1表單中沒有方法setValidatorGroup。 那么有沒有其他選擇?

表單是在xml中定義的,因此fielddefinition如下所示:

    <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;
    }

最好的問候,蒂姆·范·斯坦伯格根,tieka.nl

通常,驗證器使用可選的$context var,正像您在上面指出的那樣。 但是,您會將驗證器附加到單個字段(因此,任何驗證失敗也將附加到該字段)。

標准示例是一個注冊表單,該表單請求password值和confirm_password值。 驗證器可以附加到password字段,驗證器的isValid($value, $context = null)方法會將$value$context['confirm_password'] 如果失敗,則會在password字段中設置錯誤,然后在視圖腳本或表單修飾符中將其引用。

您可以自定義驗證器,並使用isValid的第二個參數來設置其他發布字段,如下所示:

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 Form中,只需將此驗證器綁定到您的某個字段即可(例如密碼)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM