cakephp 3.x中的复选框验证

时间:2015-12-15 10:56:17

标签: php cakephp

如何在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

4 个答案:

答案 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]);

https://book.cakephp.org/3.0/en/views/helpers/form.html#options-for-select-checkbox-and-radio-controls

答案 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;
}