[英]Conditionally required in Zend Framework's 2 InputFilter
我正在使用 Zend Framework 2 制作應用程序。我正在使用它的InputFilter
驗證輸入。 是否有可能有條件地要求某些Input
? 我的意思是我有這樣的代碼:
$filter = new \Zend\InputFilter\InputFilter();
$factory = new \Zend\InputFilter\Factory();
$filter->add($factory->createInput(array(
'name' => 'type',
'required' => true
)));
$filter->add($factory->createInput(array(
'name' => 'smth',
'required' => true
)));
我希望只有當type
等於1
時才需要字段something
。 有沒有內置的方法來做到這一點? 還是我應該只創建自定義驗證器?
首先,您可能希望從傳遞給 Zend Framework 2 驗證器的空值開始對空值/空值啟用驗證
您可以使用回調輸入過濾器,如以下示例所示:
$filter = new \Zend\InputFilter\InputFilter();
$type = new \Zend\InputFilter\Input('type');
$smth = new \Zend\InputFilter\Input('smth');
$smth
->getValidatorChain()
->attach(new \Zend\Validator\NotEmpty(\Zend\Validator\NotEmpty::NULL))
->attach(new \Zend\Validator\Callback(function ($value) use ($type) {
return $value || (1 != $type->getValue());
}));
$filter->add($type);
$filter->add($smth);
當值smth
是一個空字符串並且type
的值不是1
時,這基本上可以工作。 如果type
的值為1
,則smth
必須不同於空字符串。
我無法完全理解 Ocramius 的示例,因為 $type->getValue 始終為 NULL。 我稍微更改了代碼以使用 $context,這對我有用:
$filter = new \Zend\InputFilter\InputFilter();
$type = new \Zend\InputFilter\Input('type');
$smth = new \Zend\InputFilter\Input('smth');
$smth
->getValidatorChain()
->attach(new \Zend\Validator\NotEmpty(\Zend\Validator\NotEmpty::NULL))
->attach(new \Zend\Validator\Callback(function ($value, $context){
return $value || (1 != $context['type']);
}));
$filter->add($type);
$filter->add($smth);
您也可以為此使用setValidationGroup
。
創建您自己的InputFilter
類,您可以在其中根據在執行實際驗證之前在 inputfilter 中設置的數據設置驗證組。
class MyInputFilter extends InputFilter
{
setData($data){
if(isset($data['type']) && $data['type'] === 1){
// if we have type in data and value equals 1 we validate all fields including something
setValidationGroup(InputFilterInterface::VALIDATE_ALL);
}else{
// in all other cases we only validate type field
setValidationGroup(['type']);
}
parent::setData($data);
}
}
這只是一個簡單的例子來展示setValidatioGroup
的可能性,您可以根據您的特定需要創建自己的組合來設置驗證組。
$inputFilter->add([
'name' => 'commPersconphone1number',
'required' => (($this->session->ouCode == '50001') ? true : false),
'error_message' => $this->arrLabels['err_phone'],
'filters' => [
['name' => 'StringTrim'],
['name' => 'StripTags'],
['name' => 'StripNewlines'],
],
'validators' => [
[
'name' => 'StringLength',
'options' => [
'min' => 0,
'max' => 15,
'error_message' => $this->arrLabels['err_phone_invalid']
],
],
[
'name' => 'Regex',
'options' => [
'pattern' => '/^[0-9]*$/',
'message' => $this->arrLabels['err_phone_invalid'],
],
],
],
]);
不幸的是,您必須根據您的條件設置所需的選項,如下所示:
$filter->add($factory->createInput(array(
'name' => 'smth',
'required' => (isset($_POST['type']) && $_POST['type'] == '1'),
)));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.