How can I limit the length of <h:inputTextarea>
? For <h:inputText>
it works fine with maxlength
attribute. However, this attribute is unavailable in <h:inputTextarea>
.
If you're using HTML5 and JSF 2.2+, specify it as a passthrough attribute.
<html ... xmlns:a="http://xmlns.jcp.org/jsf/passthrough">
<h:inputTextarea value="#{bean.text}" a:maxlength="2000" />
If you're using HTML5, but not JSF 2.2 yet, use OmniFaces Html5RenderKit
to recognize new HTML5 attributes in JSF 2.0/2.1.
<h:inputTextarea value="#{bean.text}" maxlength="2000" />
If you're on HTML4, then it's already not supported by HTML itself. It's only supported on <input>
element, not on <textarea>
element. That's also why there's no such attribute on the JSF representation of this HTML element. You need to solve this requirement at the client side using JS and/or at the server side using JSF. JS enables you to instantly validate the length and ignore all other characters. JSF enables you to validate it as well for the case that the client disabled or hacked the JS code. Best would be a combination of both.
Assuming that you've a
<h:inputTextarea value="#{bean.text}" styleClass="max">
<f:validateLength maximum="2000" />
</h:inputTextarea>
here's how you could do the jQuery
$('textarea.max').keyup(function() {
var $textarea = $(this);
var max = 2000;
if ($textarea.val().length > max) {
$textarea.val($textarea.val().substr(0, max));
}
});