In yii.activeform.js
, the afterValidateAttribute
callback is documented. Compared to Yii 1.1, it no longer has the hasError
parameter. It may be due to it being redundant, however the docs doesn't tell me if I can rely on the messages
array always being empty when there are no error and always non-empty when there is an error.
Perhaps it could be documented if we can check if the messages
array is empty, or if there is another recommended way to overcome that the hasError
parameter was removed.
The reason I want to know if there is an error or not, is to update aria-invalid
attribute of the input field to reflect if there is an error or not. This tells screen readers about the error state of the input field.
Let me also say that it is nice to see that Yii 2.0 has improved forms quite a bit by offering ActiveField in the main code which I now can customize mostly by just configuring ActiveForm and ActiveField to get my desired HTML output rather than having to override significant parts of CActiveForm.
Here is my JS code for reference which appear to work. Also my study of the Yii JS says it should work, only that it would be nice if it was officially documented so that it hopefully is included in the changelog should the behaviour break in the future.
$("form").on("afterValidateAttribute", function(event, attribute, messages) {
var hasError = messages.length !==0;
var field = $(attribute.container);
var input = field.find(attribute.input);
input.attr("aria-invalid", hasError ? "true" : "false");
});
Most helpful comment
Here is my JS code for reference which appear to work. Also my study of the Yii JS says it should work, only that it would be nice if it was officially documented so that it hopefully is included in the changelog should the behaviour break in the future.