How to set maxlength attribute on h:inputTextarea

HTML5 + JSF 2.2+

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" />

HTML4

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));
    }
});

Leave a Comment