2016-07-23 7 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'); 
関連する問題