Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accept only digits for h:inputText value

Is there a way to confirm the value of an h:inputText in JSF, which should accepts only digits. Means it can be an Integer or the float.

If I type 12s3a562.675 , a5678s12 , 68712haf.563345 or any other such kind of values, then it should show an error. Otherwise it accepts and proceeds.

like image 499
abhi Avatar asked Oct 09 '13 10:10

abhi


3 Answers

<h:inputText onkeypress="if(event.which &lt; 48 || event.which &gt; 57) return false;"/> is a short way if you want to accept integers only.

It has the advantage over type="number" that you can't even enter a non-digit

like image 52
dasLort Avatar answered Nov 12 '22 04:11

dasLort


Just bind the input value to a Double, or better, BigDecimal property instead of String.

private BigDecimal number; // Double can also, but beware floating-point-gui.de
<h:inputText value="#{bean.number}" />

JSF has builtin converters for those types which will kick in automatically. You can customize the converter message as below:

<h:inputText value="#{bean.number}" converterMessage="Please enter digits only." />
like image 22
BalusC Avatar answered Nov 12 '22 05:11

BalusC


If you add this to your xhtml

xmlns:pe="http://primefaces.org/ui/extensions"

and use the inputext for numbers of Primefaces Extensions called pe:inputNumber , which not only validate your numbers but decimals also, may be more complete.

<pe:inputNumber value="#{beanTest.myValue}" thousandSeparator="" decimalSeparator="." decimalPlaces="0" />
like image 13
diego matos - keke Avatar answered Nov 12 '22 04:11

diego matos - keke