CakePHP 3:验证表格

时间:2016-07-19 16:09:59

标签: validation cakephp

我需要验证表单,但我不确切知道如何才能执行此操作。我尝试在Model / Users.php和Model / Table / UserTables.php中验证,没有。

有人可以帮助我吗?

register.ctp

<br>
<div class="index large-4 medium-4  large-offset-4 medium-offset-4 columns">
    <div class="panel">
        <h2 class="text-center">Cadastro</h2>
        <?= $this->Form->create(); ?>

            <?= $this->Form->input('nome'); ?>
            <?= $this->Form->input('email'); ?>
            <?= $this->Form->input('password'); ?>
            <?= $this->Form->submit('Cadastrar', array('class' => 'button')); ?>


        <?= $this->Form->end(); ?>
    </div>
</div>      

我不知道我可以把它放在哪里:

public $validate = array(
   //campo que deve ser validado
   ‘nome’ => array(
      //alias da validação
      ‘notempty’ => array(  
    ‘rule’=>’notempty’,//validação para não aceitar vazio
    ‘message’=>”Você deve preencher este campo”//erro
      )
   ),
   ‘idade’ => array(
    ‘notempty’ => array(
    ‘rule’ => ‘notempty’,
    ‘message’ => ‘Você deve preencher este campo’
   ),
   ‘numeric’ => array(
    ‘rule’ => ‘numeric’,
    ‘message’ => ‘Você deve preencher este campo’
   )
 )
 );
}
UsersTable.php 上的

验证仅适用于&#34;添加&#34;形式:

public function validationDefault(Validator $validator)
    {
        $validator
            ->integer('id')
            ->allowEmpty('id', 'create');

        $validator
            ->requirePresence('nome', 'create')
            ->notEmpty('nome');

        $validator
            ->email('email')
            ->requirePresence('email', 'create')
            ->notEmpty('email');

        $validator
            ->requirePresence('password', 'create')
            ->notEmpty('password');



        return $validator;
    }

1 个答案:

答案 0 :(得分:0)

您需要将验证放入模型中。看起来您正在使用cakephp 2的验证语法,但您的标题表示您使用的是版本3.您可以在此处看到:http://book.cakephp.org/2.0/en/models/data-validation.html#simple-rules

以下是cakephp 3验证的文档:http://book.cakephp.org/3.0/en/core-libraries/validation.html

您需要将其添加到模型中

use Cake\Validation\Validator;

$validator = new Validator();

从那里你可以添加像

这样的东西
$validator->notEmpty('title', 'Please fill this field')