3

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.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Rajath
  • 2,178
  • 6
  • 32
  • 38

1 Answers1

4

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.

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>

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

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • @kolossus *I want a `` which should only accept numbers and not any other characters*, so OP needs a way to validate the input in client side:. The only way to do this is using JavaScript. I assume OP would also have a server validator, but that's outside of the question. – Luiggi Mendoza Jan 30 '13 at 12:37