您需要在锚标记内显示错误文本title
属性,并使用template
选项不会帮助您自动实现它。
你的方法中有一些事情。
-
您正在指定"tag"=>null
在下面errorOptions
这不会创建默认的 html<p class="help-block help-block-error"></p>
.
-
即使您将标签指定为div
or span
即使如此,它也会破坏 HTML,因为属性标题有双引号<a href="#" title="{error}">error</a>
并且创建的标签也将带有双引号<div class="help-block help-block-error"></div>
.
-
那么如果你改变<a href="#" title="{error}">error</a>
to <a href="#" title=\'{error}\'>error</a>
修复损坏的HTML
JavaScript 将无法检测到该元素。
那么接下来的事件afterValidateAttribute
将在验证整个表单和每个属性后触发,来拯救您。
事件处理程序的签名应该是:
function (event, attribute, messages)
where
现在改变template
在下面fieldConfig
到以下内容并删除{error}
从模板和errorOptions
,因为不需要它,只需将自定义错误元素保留在模板内即可。
'fieldConfig' => [
'template' => '
{label}
<div class="error-block">
<a href="#" title="">error</a>
</div>
{input}
',
],
现在,将以下 javascript 添加到要呈现表单的视图顶部。
$js = <<< JS
$("#login-form").on(
'afterValidateAttribute',
function (event,attribute,messages) {
let input=attribute.input;
$(input).siblings('.error-block').find('a').attr('title',messages.join(','));
}
);
JS;
$this->registerJs($js, \yii\web\View::POS_READY);
现在如果你focus
超出字段或点击提交按钮,您将看到错误消息填充在title
的属性a
tag.