【问题标题】:Custom Validation Not Working- Yii2-app-basic-Yii2自定义验证不起作用 - Yii2-app-basic-Yii2
【发布时间】:2015-10-06 12:23:03
【问题描述】:

我昨天发布了一个关于单选按钮Textfield Mandatory On Radio Button 的自定义验证的问题。我得到了答案。但是,这不是确切的答案。但是,它解决了我的一个问题。

实际上,我有 2 个单选按钮。

  • 个人
  • 公司

何时,选择具有“个人”值的单选按钮,CompanyName TextBox不应该是强制性的。 But, when Radio Button having "Firm" value is selected, CompanyName textbox should be mandatory.

现在发生的事情是,当我选择单选按钮“公司”并且没有为 CompanyName 文本框填充任何值时,数据不会插入到数据库表中。美好的。这没关系。但是,错误消息未以形式显示。选择 Radio Button Firm 后,错误消息应显示为 CompanyName 文本框是必需的。

我没有得到我做错的地方。这是我的视图、控制器和模型代码。请帮帮我。

register.php(查看)

<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\captcha\Captcha;
use yii\bootstrap\Modal;
use yii\helpers\Url;
?>

<?php $form = ActiveForm::begin(['id' => 'register-form']); ?>
    .
    .
    .
    <?= $form->field($model, 'AdminType')
            ->radioList(array('Individual'=>'An Individual', 'Firm'=>'Firm/Company'))
            ->label('Are You')?>
    <?= $form->field($model, 'CompanyName')->textInput()->label('Company Name')->error() ?>
    .
    .
<?php ActiveForm::end(); ?>

SiteController.php(控制器)

<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\swiftmailer\Mailer;
use app\models\RegisterForm;

public function actionRegister()
{
    // Register Model
    $model = new RegisterForm();
    if ($model->load(Yii::$app->request->post())) 
    {
        $post = Yii::$app->request->post('RegisterForm');
        if ($model->validate())
        {

        }
        else
        {
            // HERE YOU CAN PRINT THE ERRORS OF MODEL
            echo "<pre>";
            print_r($model->getErrors());
            echo "</pre>";
        }
        return $this->refresh();
    }

}

RegisterForm.php(型号)

<?php

namespace app\models;

use Yii;
use yii\base\Model;
use kartik\password\StrengthValidator;


class RegisterForm extends Model
{
    public $fname;
    public $lname;
    public $email;
    public $password;
    public $confirmPassword;
    public $AdminType;
    public $CompanyName;
    public $verifyCode;

    public function rules()
    {
        return [
                [['fname','lname', 'email', 'password','confirmPassword','verifyCode','AdminType'], 'required'],
                ['email', 'email'],
            ['confirmPassword', 'compare', 'compareAttribute' => 'password'], 
                ['verifyCode', 'captcha'],

        //add rule that uses the validator function
                ['AdminType','radioValidator'],
        ];
    }

    //implement the validator
    public function radioValidator($attribute)
    {
        if($this->$attribute === 'Firm')
            return $this->addError('CompanyName', 'Company Name cannot be blank');
    }
}

【问题讨论】:

  • 您是否验证 RegisterForm? $model-&gt;validate()
  • 哦.. 对不起 @Sergey 先生。我没有包括在这里。是的。但是 @model->validate() 存在于我的控制器中。我刚刚编辑了我的问题。
  • 在将render 模板调用到Controller 的地方,您可能不会显示完整的控制器类 - 只有一种方法

标签: php yii2 custom-validators yii2-basic-app


【解决方案1】:

您应该在ActiveForm 中添加'enableAjaxValidation' =&gt; true

完成此操作后,您的代码应该是,

控制器

public function actionRegister()
{
    $model = new RegisterForm();
    if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
      \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
      return \yii\widgets\ActiveForm::validate($model);
    }

    if ($model->load(Yii::$app->request->post())) 
    {
    }
    else
    {
        // HERE YOU CAN PRINT THE ERRORS OF MODEL
        echo "<pre>";
        print_r($model->getErrors());
        echo "</pre>";
    }
    return $this->refresh();
}

查看

<?php $form = ActiveForm::begin([
           'id' => 'register-form',
           'enableAjaxValidation' => true,
]); ?>
    .
    .
    .
    <?= $form->field($model, 'AdminType')
            ->radioList(array('Individual'=>'An Individual', 'Firm'=>'Firm/Company'))
            ->label('Are You')?>
    <?= $form->field($model, 'CompanyName')->textInput()->label('Company Name')->error() ?>
    .
    .
<?php ActiveForm::end(); ?>

也许对你有帮助。

【讨论】:

  • 好的。让我检查 @gamitg 先生。
  • 在编辑我的代码后,@gamitg 先生您所说的内容。现在,表单没有被提交。意味着,现在提交按钮充当普通按钮。不,提交任何东西。
  • 查看萤火虫控制台中的错误。发生了什么错误?
  • 选择 FIRM 后现在显示错误。但是,验证码显示“验证码不正确。”。而且,在那之后我没有碰任何东西。而且,还有一件事,即使在选择了单选按钮 INDIVIDUAL 之后,表单也没有提交。我想是因为验证码。
  • 我想你已经接近回答 @gamitg 先生了。你的工作,但现在验证码因此无法工作。
【解决方案2】:

终于,我得到了答案

     //company_name
      ['company_name', 'required', 'when' => function($model){
        return ($model->user_type == 'Firm' ? true : false);
      }, 'whenClient' => "function (attribute, value) {
          return $('input[type=\"radio\"][name=\"Users[user_type]\"]:checked').val() == 'Firm';
      }"],

【讨论】:

    【解决方案3】:

    @娜娜派对卡

    当您询问如何为验证码禁用 ajax 验证时,我尝试过这种方式。但我不确定这是否是正确的方法。

    我已经用这个设置设置了表单

    'enableAjaxValidation' => true,
    'enableClientValidation' => false,
    'validateOnSubmit' => false,
    

    并将操作的验证更改为此(在我的案例中,我从应该验证的属性中删除了我的验证码“verifyCode”。

    if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = 'json';
            $validateAttributes = $model->activeAttributes();
            $key = array_search('verifyCode', $validateAttributes);
            if ($key!==false) {
                array_splice($validateAttributes, $key, 1);
            }
            return \yii\widgets\ActiveForm::validate($model, $validateAttributes);
    }
    

    【讨论】:

      【解决方案4】:

      其实你的操作方法不对。当您调用 refresh() 时,您基本上会重新加载页面。如果模型尚未在数据库中更新,您将不会看到任何特殊情况,并且在重新加载新模型后也不会出现错误。

      此代码将照常在您的视图中显示错误:

         /**
           * @return \yii\web\Response
           */
          public function actionRegister()
          {
              // Register Model
              $model = new RegisterForm();
              if ($model->load(Yii::$app->request->post()))
              {
                  $post = Yii::$app->request->post('RegisterForm');
                  if ($model->validate())
                  {
                       // whatever
                  }
      
      //            return $this->refresh(); // do not refresh but...
              }
      
              // ... render the view with the current model, who's errors attribute is filled
              return $this->render('register', compact('model'));
          }
      

      注意:另外,您不必在视图中调用 errors(),ActiveFormField 渲染方法会为您处理:

      <?= $form->field($model, 'CompanyName')->textInput()->label('Company Name') ?>
      

      够了

      【讨论】:

        【解决方案5】:

        如果您在没有选项的情况下调用 error,则会抑制错误输出

        ActiveField error 方法

        yii\widgets\ActiveField

        public function error($options = [])
        {
            if ($options === false) {
                $this->parts['{error}'] = '';
                return $this;
            }
            $options = array_merge($this->errorOptions, $options);
            $this->parts['{error}'] = Html::error($this->model, $this->attribute, $options);
        
            return $this;
        }
        

        您必须将调用 error 方法删除到 VIEW 中

        <?= $form->field($model, 'CompanyName')->label('Company Name')->textInput() ?>
        

        【讨论】:

        • @NanaPartykar,我发现你的错误 - 我会更新我的答案
        猜你喜欢
        • 1970-01-01
        • 2015-12-26
        • 1970-01-01
        • 2016-11-20
        • 1970-01-01
        • 1970-01-01
        • 2015-06-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多