如何在cakephp 3.0
在cakephp 2.x
中,验证就像:
'accept_terms' => array(
'rule' => array('comparison', '!=', 0),
'required' => true,
'message' => 'You must agree to the terms',
'on' => 'create',
),
我想将其转换为cakephp 3.x
。
答案 0 :(得分:0)
验证复选框没有特殊规则。您要做的是在notEmpty
上验证该字段为create
: -
$validator
->requirePresence('accept_terms')
->notEmpty('accept_terms', 'You must agree to the terms', 'create');
这可以在official docs on Validation中找到。可用验证规则的完整列表可以是found in the API docs。
答案 1 :(得分:0)
您可以使用自定义方法对您的复选框进行验证。我喜欢这个。这对我来说没问题。
public function validationBooking(Validator $validator)
{
$validator->add('accept_terms', 'custom', [
'rule' => [$this, 'AcceptTerm'],
'message' => 'You must agreed Term and Condition'
]);
return $validator;
}
//make function
public function AcceptTerm($value,$context){
if($context['data']['accept_terms']==1)
return true;
else
return false;
}
答案 2 :(得分:0)
您可以通过requirePresence
-Validation-Method来检查复选框是否已选中。
在您的模型中:
$validator
->boolean('accept_legalnotice')
->requirePresence('accept_legalnotice', true, 'You have to accept.');
要完成此工作,您需要禁用表单帮助程序生成的复选框的隐藏字段。
您认为:
echo $this->Form->checkbox('accept_legalnotice', ['hiddenField' => false]);
答案 3 :(得分:0)
在CakePHP 3.x中
表格
<?= $this->Form->create($user) ?>
<?= $this->Form->control('username'); ?>
<?= $this->Form->control('password'); ?>
...
<?= $this->Form->control('term_and_conditions'); ?>
<?= $this->Form->submit(__('Save')); ?>
<?= $this->Form->end(); ?>
模型: Validator :: equals($ field,$ value,$ message = null,$ when = null)允许您检查是否已选中复选框
public function validationDefault(Validator $validator)
{
...
$validator
->boolean('term_and_conditions')
->requirePresence('term_and_conditions', 'create')
->equals('term_and_conditions', true);
...
return $validator;
}