在某些情况下允许空验证

时间:2016-07-23 09:22:04

标签: cakephp cakephp-3.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');

1 个答案:

答案 0 :(得分: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');