问题
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>
.
回答1:
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));
}
});
回答2:
<h:inputTextarea required="true" cols="50" rows="5" id=”aboutMe” value="#{person.aboutMe}”>
<f:validateLength maximum="400" minimum="20"/>
</h:inputTextarea>
回答3:
BalusC's answer is good, but please be warned the JSF validator, invoked with f:validateLength maximum="2000" />
, will count new line characters twice whereas $textarea.val().length
will only count them once. You'll need to double count the newline breaks in your JavaScript validator if you want the two validators to return the same results for multiline inputs.
An example of this issue would be an input of "Hello\nWorld"
in your text area, where \n is actually a line break. This would be counted as 12 characters by the JSF validator, but $textarea.val().length
would only return 11. This discrepancy will obviously get worse if you're letting the user input multiple paragraphs.
Although not about the same subject, the first couple of paragraphs of this article have an explanation for the JavaScript behaviour. There are also some comments about this exact issue that may be of use.
来源:https://stackoverflow.com/questions/4923573/how-to-set-maxlength-attribute-on-hinputtextarea