【问题标题】:Custom ajax validation for text length doesn't work yii2文本长度的自定义 ajax 验证不起作用 yii2
【发布时间】:2017-07-04 12:30:26
【问题描述】:

我正在尝试检查输入文本的长度,但没有成功。它与required 规则一起使用,因为我收到the field is empty 错误,但没有通过我的验证。我的自定义规则仅适用于表单提交。还尝试启用表单的 ajax 验证,但还是没有。

public function rules()
    {
        return [
            [['author_id', 'title', 'review'], 'required'],
            [['author_id'], 'integer'],
            [['review'], 'string'],
            [['review'], function($attribute, $params){
                if(strlen($this->$attribute) < 10){
                    $this->addError($attribute, 'The review is too short! Minimum 10 symbols!');
                }
            }],
            [['review'], 'trim'],
            [['dt'], 'safe'],
            [['title'], 'string', 'max' => 255],
            [['author_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['author_id' => 'id']],
            [['post_id'], 'exist', 'skipOnError' => true, 'targetClass' => News::className(), 'targetAttribute' => ['post_id' => 'id']],
        ];
    }

我的表格:

<?php $form=\yii\bootstrap\ActiveForm::begin([
                                'method' => 'post',
                                'options' => [
                                    'id' => 'textarea_' . $model->id . '',
                                    'class' => "textarea_review"
                                ],

                            ]) ?>

                            <input type="hidden" name="flag" value="1"/>
                            <input type="hidden" name="model_id" value="<?= $model->id ?>"/>
                            <?= $form->field($model, 'review')->textarea(['id'=>'update_text_'.$model->id.''])->label(false) ?>
                            <?= $form->field($model, 'csrf_token')->hiddenInput(['value' => $session['token']])->label(false) ?>

                            <?= Html::button('Изпрати', ['onclick'=>'editComment('.$model->id.')', 'class'=>'btn btn-primary send-button']) ?>
                            <?php \yii\bootstrap\ActiveForm::end() ?>

提前谢谢你!

【问题讨论】:

    标签: yii2


    【解决方案1】:

    也许跳过内联验证器并定义string 规则如下是最适合您的解决方案:

    [['review'], 'string', 'max' => 10, 'message' =>  'The review is too short! Minimum 10 symbols!']
    

    如果您绝对需要自定义验证器,第二好的选择是 使用 ajax 验证。

    如果以上都不适合您,那么您将无法仅仅编写 php 验证规则。 您需要提供客户端脚本以在浏览器中实现相同的验证逻辑。

    要么定义一个自定义验证器类并覆盖clientValidateAttribute() 或者您可以为您在自定义规则中使用的内联验证器指定 clientValidate 属性。
    确保在阅读文档时遵循 yii\validators\InlineValidatoryii\validators\Validator 之间的区别

    【讨论】:

    • 谢谢!现在我将使用第一个选项。它现在适合我:)
    【解决方案2】:

    对于客户端验证,您还必须设置 whenClient 属性,用于放置 javascript 验证。

    这里的文档:Client Side Validation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-26
      • 1970-01-01
      • 2015-06-14
      • 1970-01-01
      • 2016-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多