2015-12-25 81 views
0

我的ZF1表單具有相互關聯的fieldland和fieldnumber,我需要檢查兩者是否都填充。如何做這個驗證?在ZF1表單中沒有方法setValidatorGroup。那麼有沒有其他的選擇?Zend框架1:兩個相關字段的表單驗證

的形式是一個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> 

我希望需要的ValidationGroup,首先是對的選擇嗎?其次,如何在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

+0

但是爲什麼?對一個字段顯示一個錯誤,對其他字段顯示其他錯誤。這是應用程序的預期行爲。 – Deep

回答

0

通常情況下,驗證使用可選$context VAR,正是因爲你在上面顯示。但是您將驗證器附加到單個字段(因此任何驗證失敗也將附加到該字段)。

標準示例是一個註冊表單,用於請求password值和confirm_password值。驗證器可以附加到password字段,驗證器的isValid($value, $context = null)方法將比較$value$context['confirm_password']。然後,失敗將在password字段上設置錯誤,然後在視圖腳本或表單裝飾器中引用該錯誤。

0

你可以有你自定義的驗證,並使用可用的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表格

然後就這個驗證綁定到你的領域之一(只說密碼)