繁体   English   中英

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

[英]Custom Validation Not Working- Yii2-app-basic-Yii2

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

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

  • 个人
  • 公司

当选择具有“个人”值的单选按钮时,CompanyName文本框不应是必需的。 但是,当选择具有“固定”值的单选按钮时,CompanyName文本框应该是必需的。

现在发生了什么,当我选择单选按钮'Firm'并且没有填写CompanyName文本框的任何值时,数据不会插入数据库表中。 精细。 哪个可以。 但是,错误消息未以表单形式显示。 选择单选按钮固件后,应显示错误消息,因为CompanyName文本框是必需的。

我没有到达我犯错误的地方。 这是我的视图,控制器和型号代码。 请帮我。

register.php (VIEW)

<?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 (CONTROLLER)

<?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 (MODEL)

<?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();
}

视图

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

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

ActiveField error方法

警予\\小工具\\ 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() ?>

@Nana Partykar

当你问我如何为验证码禁用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);
}

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

足够

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM