Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

validation - How to set maxlength attribute on h:inputTextarea

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>.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

HTML5 + JSF 2.0/2.1

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...