Yii2 文本长度的自定义ajax验证不需要';我不工作
我试图检查输入的文本长度,但没有成功。它正在使用Yii2 文本长度的自定义ajax验证不需要';我不工作,yii2,Yii2,我试图检查输入的文本长度,但没有成功。它正在使用required规则,因为我得到字段为空错误,但没有使用我的验证。我的自定义规则仅适用于表单提交。还尝试启用表单的ajax验证,但再次失败 public function rules() { return [ [['author_id', 'title', 'review'], 'required'], [['author_id'], 'integer'],
required
规则,因为我得到字段为空
错误,但没有使用我的验证。我的自定义规则仅适用于表单提交。还尝试启用表单的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']],
];
}
公共功能规则()
{
返回[
[['author_id','title','review'],'required'],
[['author_id'],'integer'],
[['review'],'string'],
['review'],函数($attribute,$params){
if(strlen($this->$属性)<10){
$this->addError($attribute,'评论太短了!最少10个符号!');
}
}],
[review'],[trim'],
[['dt'],'safe'],
[['title'],'string','max'=>255],
[['author\u id']、'exist'、'skipOnError'=>true、'targetClass'=>User::className()、'targetAttribute'=>['author\u 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() ?>
对于客户端验证,您还必须设置whenClient
属性,将javascript验证放在其中
这里的文档:也许跳过内联验证器并定义字符串
规则对您来说是最好的解决方案:
[['review'], 'string', 'max' => 10, 'message' => 'The review is too short! Minimum 10 symbols!']
如果您绝对需要自定义验证器,第二个最好的选择是
使用ajax验证
如果以上两种方法都不适合您,那么您就不能仅仅编写php验证规则。
您需要提供客户端脚本以在浏览器中实现相同的验证逻辑
定义一个自定义验证器类并重写
或者,您可以为自定义规则中使用的内联验证程序指定属性。
在阅读文档时,请确保遵循yii\validators\InlineValidator
和yii\validators\Validator
之间的区别谢谢!现在我将使用第一个选项。它现在适合我:)