如何在 h:inputTextarea 上设置 maxlength 属性 [英] How to set maxlength attribute on h:inputTextarea
问题描述
如何限制
的长度?对于
它与 maxlength
属性一起工作正常.但是,该属性在
中不可用.
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>
.
推荐答案
HTML5 + JSF 2.2+
如果您使用 HTML5 和 JSF 2.2+,请将其指定为 passthrough 属性.
<html ... xmlns:a="http://xmlns.jcp.org/jsf/passthrough">
<h:inputTextarea value="#{bean.text}" a:maxlength="2000" />
HTML5 + JSF 2.0/2.1
如果您使用的是 HTML5,但还不是 JSF 2.2,请使用 OmniFaces Html5RenderKit
以识别 JSF 2.0/2.1 中的新 HTML5 属性.
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
如果您使用的是 HTML4,则 HTML 本身已经不支持它.它仅支持 元素,不支持
元素.这也是为什么此 HTML 元素的 JSF 表示上没有此类属性的原因.您需要在客户端使用 JS 和/或在服务器端使用 JSF 解决此需求.JS 使您能够立即验证长度并忽略所有其他字符.JSF 还允许您在客户端禁用或破解 JS 代码的情况下对其进行验证.最好是两者结合.
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.
假设你有一个
<h:inputTextarea value="#{bean.text}" styleClass="max">
<f:validateLength maximum="2000" />
</h:inputTextarea>
这里是你可以如何做 jQuery
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));
}
});
这篇关于如何在 h:inputTextarea 上设置 maxlength 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!