2016-07-23 71 views
0

我想驗證基於數據庫數據的郵政編碼,如果這個國家是否需要這個數據以及哪個格式。允許在某些情況下進行空驗證

我目前在模型中有以下驗證規則。唯一的問題是,如果沒有提供郵政編碼驗證規則沒有觸發。有什麼建議麼?

$validator 
     ->requirePresence('postalcode', 'true') 
     ->add('postalcode', [ 
      'shouldHavePostalCode' => [ 
       'rule' => function ($value, $context) { 
        $countriesTable = TableRegistry::get('Countries'); 

        $country = $countriesTable->findByIsoCode($context['data']['country'])->first(); 

        if(is_null($country)) { 
         return 'postcode kon niet gecontroleerd worden door ongeldig land'; 
        } 

        return $country->need_postalcode; 
       }, 
       'message' => 'Verplicht voor dit land', 
      ], 
      'validPostalCode' => [ 
       'rule' => function ($value, $context) { 
        $countriesTable = TableRegistry::get('Countries'); 

        $country = $countriesTable->findByIsoCode($context['data']['country'])->select(['postalcode_format', 'iso_code'])->first(); 

        if (empty($country->postalcode_format)) { 
         return true; 
        } 
        $zip_regexp = '/^'.$country->postalcode_format.'$/ui'; 
        $zip_regexp = str_replace(' ', '(|)', $zip_regexp); 
        $zip_regexp = str_replace('-', '(-|)', $zip_regexp); 
        $zip_regexp = str_replace('N', '[0-9]', $zip_regexp); 
        $zip_regexp = str_replace('L', '[a-zA-Z]', $zip_regexp); 
        $zip_regexp = str_replace('C', $country->iso_code, $zip_regexp); 

        if((bool)preg_match($zip_regexp, $value)) { 
         return true; 
        } 
        return 'Ongeldige indeling (' . $country->postalcode_format . ')'; 
       }, 
      ] 
     ]) 
     ->allowEmpty('postalcode'); 

回答

0

沒關係,下面的伎倆。

->allowEmpty('postalcode', function($context) { 
    if(!isset($context['data']['country']) || empty($context['data']['country'])) { 
     return true; 
    } 

    $countriesTable = TableRegistry::get('Countries'); 

    $country = $countriesTable->findByIsoCode($context['data']['country'])->first(); 

    if(is_null($country)) { 
     return 'postcode kon niet gecontroleerd worden door ongeldig land'; 
    } 

    return !$country->need_postalcode; 
}, 'Verplicht');