如何在Primefaces输入文本中禁用特殊字符和字母? [英] How to disable special characters and alphabets in Primefaces input text?

查看:102
本文介绍了如何在Primefaces输入文本中禁用特殊字符和字母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个<p:inputText>,它只能接受数字,不能接受任何其他字符.是否有可能使用户只能输入数字而其他字符被禁用?如果是这样,请告诉我.

I want a <p:inputText> which should only accept numbers and not any other characters. Is it possible so that the user can only type in numbers and the other characters are disabled? If so, please let me know how.

推荐答案

最后,<h:inputText><p:inputText>组件将呈现一个<input type="text" /> HTML组件.您唯一需要做的就是应用JavaScript方法来限制文本中允许使用的字符.

In the end, the <h:inputText> and <p:inputText> components will render an <input type="text" /> HTML component. The only thing you need is to apply a JavaScript method to restrict the characters that will be allowed in the text.

知道这一点后,您可以使用问题 HTML文本输入仅允许数字输入中提供的任何方法.我将基于帖子的第二个答案向您展示一个示例:

Knowing this, you can use any of the methods provided in the question HTML Text Input allow only Numeric input. I'll show you an example based on the second answer of the post:

<h:head>
    <script type="text/javascript">
        //<![CDATA[
        var numericRegex = /\d+\.?\d*/;
        function validateNumericInput(evt, text) {
            var theEvent = evt || window.event;
            var key = theEvent.keyCode || theEvent.which;
            key = String.fromCharCode( key );
            if (key === '.') {
                theEvent.returnValue = (text.indexOf(key) < 0);
            } else {
                var regex = /\d/;
                if( !regex.test(key) ) {
                    theEvent.returnValue = false;
                    if(theEvent.preventDefault) theEvent.preventDefault();
                }
            }
        }
        //]]>
    </script>
</h:head>
<h:body>
    Try to write a non-numeric
    <p:inputText onkeypress="validateNumericInput(event, this.text)" />
</h:body>

请注意,此示例仅允许写入正实数,只需更改JavaScript方法以定义其他行为即可.

Note that this example only allows to write positive real numbers, just change the JavaScript method to define a different behavior.

这篇关于如何在Primefaces输入文本中禁用特殊字符和字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆