自定义验证不起作用- Yii2-app-basic-Yii2


Custom Validation Not Working- Yii2-app-basic-Yii2

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

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

    个人公司

当选择具有"Individual"值的单选按钮时,CompanyName文本框不应该是强制性的。但是,当选择具有"Firm"值的单选按钮时,CompanyName文本框应该是必填的。

现在发生的事情是,当我选择单选按钮'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');
    }
}

您应该在ActiveForm中添加'enableAjaxValidation' => 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();
}
<<p> 视图/strong>
<?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(); ?>

可能对你有帮助。

最后,我得到了我的答案

     //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';
      }"],

@Nana Partykar

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

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

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

并将操作的验证更改为此(我从应该验证的属性中删除了我的captcha '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);
}

实际上,你的动作方法是不正确的。当调用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') ?>
足够

如果你调用error没有选项,你会抑制错误输出

ActiveField error method

yii '部件' 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() ?>