如何在php表单中进行验证

如何在php表单中进行验证,php,cakephp-3.0,Php,Cakephp 3.0,这是我的蛋糕phpadd.ctp文件 <h2>Add New User</h2> <!-- link to add new users page --> <div class='upper-right-opt'> <?php echo $this->Html->link( 'List Users', array( 'action' => 'index' ) ); ?> </div> <?php

这是我的蛋糕php
add.ctp
文件

<h2>Add New User</h2>

<!-- link to add new users page -->
<div class='upper-right-opt'>
  <?php echo $this->Html->link( 'List Users', array( 'action' => 'index' ) ); ?>
</div>

<?php 
 //this is our add form, name the fields same as database column names
  echo $this->Form->create('User');

  echo $this->Form->input('firstname');
  echo $this->Form->input('lastname');
  echo $this->Form->input('mobile');
  echo $this->Form->input('email');
  echo $this->Form->input('username');
  echo $this->Form->input('password', array('type'=>'password'));

 echo $this->Form->end('Submit');
?>


 <?php

任何人都可以帮助我使用controller在我的
add.ctp
文件中进行验证。

我喜欢使用进行验证,因为它可以将验证与实体和保存逻辑分开。您可以这样实现它:

创建您的表单

// in src/Form/UserForm.php
namespace App\Form;

use Cake\Form\Form;
use Cake\Form\Schema;
use Cake\Validation\Validator;

class UserForm extends Form
{

    protected function _buildSchema(Schema $schema)
    {
        return $schema->addField('firstname', 'string')
            ->addField('lastname', ['type' => 'string'])
            ->addField('mobile', ['type' => 'string'])
            ->addField('email', ['type' => 'string'])
            ->addField('username', ['type' => 'string'])
            ->addField('password', ['type' => 'string']);
    }

    protected function _buildValidator(Validator $validator)
    {
        return $validator->add('firstname', 'length', [
                'rule' => ['minLength', 3],
                'message' => 'A name is required'
            ])->add('email', 'format', [
                'rule' => 'email',
                'message' => 'A valid email address is required',
            ]);
    }

    protected function _execute(array $data)
    {
        // Send an email.
        return true;
    }
}
您可以在buildValidator中添加您喜欢的任何规则

在控制器中使用它:

use App\Form\UserForm;

...

$form = new UserForm();
if ($this->request->is('post')) {
    if ($form->execute($this->request->data)) {
        //val ok
    } else {
        $this->Flash->error('Plese correct the form errors.');
    }
}
$this->set('form', $form);
更改视图以使用表单

echo $this->Form->create($form);

我知道KaushikMaheta。你能给我们做个工具吗。我们为此感到非常高兴。非常感谢。
echo $this->Form->create($form);