Reputation: 2188
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.
Upvotes: 3
Views: 5538
Reputation: 85779
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.
Upvotes: 4