Yii验证规则忽略“ on”或“ except”

时间:2020-10-21 10:14:16

标签: forms validation yii2 scenarios

我面临下一个问题。 我正在尝试以不同的方式验证字段,具体取决于操作:电话在用户创建时应该是唯一的,而不应该在用户编辑时是唯一的,所以:

    public function rules()
{
    return [
        [['owner_id','card_code', 'name', 'phone', 'birthday','language', 'last_ip'], 'required'],
        [['account_id'], 'required', 'on' => 'update'],
        [['account_id'], 'exist', 'skipOnError' => true, 'targetClass' => Accounts::className(), 'targetAttribute' => ['account_id' => 'id'], 'on' => 'update'],

        [['owner_id', 'account_id', 'active', 'last_carwash'], 'integer'],
        [['birthday', 'last_active', 'last_update', 'last_sync'], 'safe'],
        [['car_number', 'role', 'status'], 'string'],
        [['card_code', 'car_number', 'name', 'phone', 'password', 'auth_key', 'language'], 'string', 'max' => 255],
        [['last_ip'], 'ip'],
        [['name'], 'string', 'min' => 5],

        ['password', 'string', 'min' => 6, 'message' => Yii::t('app', 'The password must contain at least 6 symbols.')/*, 'on' => 'create'*/],
        ['password', 'match', 'pattern' => '/[A-z]/', 'message' => Yii::t('app', 'The password must contain at least 1 letter.')/*, 'on' => 'create'*/],
        ['password', 'match', 'pattern' => '/[0-9]/', 'message' => Yii::t('app', 'The password must contain at least 1 number.')/*, 'on' => 'create'*/],
        [['password'], 'required', 'on' => 'create'],
        [['phone'], 'validatePhone', 'except' => 'update'/*, 'skipOnEmpty' => false*/],
        [['email'], 'email'],
        [['email'], 'validateEmail', 'except' => 'update'/*, 'skipOnEmpty' => false*/],
    ];
}

我正在使用AJAX验证:

$form = ActiveForm::begin([
        'enableAjaxValidation' => true,
        'validationUrl' => \yii\helpers\Url::to('/user/validation'),
    ]);

验证动作:

public function validatePhone()
  
  {
        $phone = preg_filter( '/[^0-9]*/','', $this->phone );
        $u = Users::findOne(['phone' => $phone]);
        if($u)
            /*if($this->id != $u->id)*/
                $this->addError('phone', Yii::t('app', 'This phone is already taken.'));
    }
    public function validateEmail()
    {
        $email = $this->email;
        if (!filter_var($email, FILTER_VALIDATE_EMAIL))
            $this->addError('email', Yii::t('app', 'Please, enter correct email'));
    
        $u = Users::findOne(['email' => $email]);
        if($u)
            $this->addError('email', Yii::t('app', 'This email is already taken.'));
    }

在控制器操作中

   public function actionCreate()
        {
            if ( Yii::$app->request->post() != NULL ) {
            $data = Yii::$app->request->post('Users');
            $model = new Users;
            $model->scenario = 'create';
           ...//lots of a code
            if(!$model->validate()){var_dump($model->errors);exit;}
            $model->save();
             return $this->redirect(['view', 'id' => $model->id]);
        }

    public function actionUpdate($id)
        {
          $model = $this->findModel($id);
          $model->scenario = 'update';
          $model->setScenario('update');// same as ^ , but who knows...
         $data = Yii::$app->request->post();

         if( $data )
         {
        ...//lots of code
           if(!$model->validate()){var_dump($model->errors);exit;}
           $model->save();
             return $this->redirect(['view', 'id' => $model->id]);
          }
         return $this->render('update', [
            'model' => $model,
          ]);
       }

public function actionValidation()
    {
        if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

            $model = new \app\models\Users();
            if($model->load(Yii::$app->request->post()))
                return \yii\widgets\ActiveForm::validate($model);
        }
        throw new \yii\web\BadRequestHttpException( Yii::t('app', 'Bad request.') );
    }

    protected function findModel($id)
        {
            if (($model = Users::findOne($id)) !== null) {
                return $model;
            }
            throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
        }

场景:

public function scenarios()
    {
        $scenarios = parent::scenarios();
        $scenarios['create'] = ['account_id', 'card_code', 'name', 'phone', 'email', 'car_number', 'birthday', 'role', 'password'];
        $scenarios['update'] = ['account_id', 'card_code', 'name', 'phone', 'email', 'car_number', 'birthday', 'role', 'password'];
        return $scenarios;
    }

但它根本不以任何形式起作用。

如果我删除'on' => 'create'可以正常工作,但是以所有形式,都是不需要的。 那么,如何仅在创建方案中使用validatePhone和validateEmail?

0 个答案:

没有答案