如何设置cakephp 3电子邮件唯一验证

时间:2018-05-14 07:57:54

标签: validation cakephp cakephp-3.0

我创建了一个包含2个字段id(primary)的表用户,(email) 我希望在代码之后使用电子邮件唯一验证,但不能只使用空工作。

<?php
namespace App\Controller;
use App\Model\Validation\UserValidator;
class UsersController extends AppController
{
public function register()
{
$this->loadModel("users");  
if ($this->request->is('post')) {
$validator = new UserValidator();
$errors = $validator->errors($this->request->getData());
 if (empty($errors)) {

      } else {
        $this->set('errors', $errors);
      }
}
}
}

的src /型号/验证/ UserValidator.php

<?php 
namespace App\Model\Validation;
use Cake\Validation\Validator;
use Cake\ORM\Table;
use Cake\ORM\Rule\IsUnique;
class UserValidator extends Validator {
  public function __construct()
  {
  parent::__construct();
    $this
    ->notEmpty('name', 'The name field cannot be left empty')
    ->notEmpty('email', 'Fill Valid Email Id')
    ->add('email',['unique' => ['rule' => 'validateUnique', 'provider' => 'table', 'message' => 'Not unique']])
    ->notEmpty('mobile', 'Fill Valid 10 Digit Mobile No.');
  }
}

1 个答案:

答案 0 :(得分:2)

在\ src \ Model \ Table \ Userstable.php

下创建此文件

已更新

更改文件名大写以使其\ src \ Model \ Table \ UsersTable.php

在我的代码中,我验证了我的用户名和电子邮件是唯一的     

use App\Model\Entity\User;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use Cake\ORM\Rule\IsUnique;
/**
 * Users Model
 *
 */
class UsersTable extends Table
{

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);
        $this->table('users');


    }

    /**
     * Default validation rules.
     *
     * @param \Cake\Validation\Validator $validator Validator instance.
     * @return \Cake\Validation\Validator
     */
    public function validationDefault(Validator $validator)
    {



       $validator
        ->requirePresence('username','create')
        ->notBlank('username', 'A username is required')
        ->add('username', 'unique', [
                    'rule' => 'validateUnique',
                    'provider' => 'table',
                    'message' => 'Username is already used'
             ]);


       $validator
        ->requirePresence('email','create')
        ->notBlank('email', 'An email is required')
        ->add('email', 'unique', [
                    'rule' => 'validateUnique',
                    'provider' => 'table',
                    'message' => 'Email is already used'
             ]);





 return $validator;

    }


    public function buildRules(RulesChecker $rules)
    {
       $rules->add($rules->isUnique(['username']));
       $rules->add($rules->isUnique(['email']));
        return $rules;  

    }

}