【问题标题】:cakephp notempty and unique validation on fieldcakephp notempty 和唯一的字段验证
【发布时间】:2017-05-11 08:04:10
【问题描述】:

我正在使用 cakephp。我需要在电子邮件字段上添加三个验证。如果未提供电子邮件,则第一次验证,第二次验证有效的电子邮件地址,第三次如果提供了电子邮件地址,则它应该是唯一的。因为它是一个注册表单。

我如何在一个字段上添加三个验证,我尝试使用以下代码,但它对我不起作用。

public $validate = array(
        'email' => array(
            'email' => array(
                'rule' => array('email'),
                'message' => 'Invalid email address',
                'allowEmpty' => false,
                //'required' => false,
                //'last' => false, // Stop validation after this rule
                //'on' => 'create', // Limit validation to 'create' or 'update' operations
            )
        ),
        'email' => array(
                'rule'    => 'isUnique',
                'message' => 'Email already registered'
            ) 
);

【问题讨论】:

    标签: validation cakephp


    【解决方案1】:

    您有两个相同的索引“电子邮件”,PHP 不允许您这样做。更改为:-

    array(
        'email' => array(
            'notEmpty' => array(
                'rule' => 'notEmpty',
                'message' => 'Provide an email address'
            ),
            'validEmailRule' => array(
                'rule' => array('email'),
                'message' => 'Invalid email address'
            ),
            'uniqueEmailRule' => array(
                'rule' => 'isUnique',
                'message' => 'Email already registered'
            )
        )
    );
    

    否则只会使用您的一条规则。

    【讨论】:

    • 它像这样工作
       'email'=>array( 'notempty'=>array( 'rule'=>'notempty', 'message'=>'Required Field' ), ' email'=>array('rule'=>'email', 'message'=>'输入有效邮箱'), 'isUnique'=>array('rule'=>'isUnique', 'message'=>'Email已经存在')) 
    【解决方案2】:

    从实体表中的 cakephp 3.0 开始,它应该看起来像这样

    namespace App\Model\Table;
    
    public function validationDefault($validator)
    {
    $validator
        ->email('email')
        ->add('email', 'email', [
            'rule' => [$this, 'isUnique'],
            'message' => __('Email already registered')
        ])
        ->requirePresence('email', 'create')
        ->notEmpty('email', 'Email is Required', function( $context ){
            if(isset($context['data']['role_id']) && $context['data']['role_id'] != 4){
                return true;
            }
            return false;
        });
     return $validator;
     }
    }
    
    
    function isUnique($email){
    $user = $this->find('all')
        ->where([
                'Users.email' => $email,
          ])
        ->first();
        if($user){
            return false;
        }
        return true;
    }
    

    【讨论】:

      【解决方案3】:

      你用的是什么版本的 Cakephp?

      因为我觉得如果你用2.3的话应该是:

      public $validate = array( 'email' => 'email' );
      

      将 SQL 表中的字段 email 设置为主键。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-24
        相关资源
        最近更新 更多