Accept only digits for h:inputText value

2019-01-17 22:44发布

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.

10条回答
▲ chillily
2楼-- · 2019-01-17 23:13

Try this

<h:inputText>
   <f:validateRegex pattern="\d*(.\d+)?"/>
</h:inputText>
查看更多
虎瘦雄心在
3楼-- · 2019-01-17 23:14

<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

查看更多
Anthone
4楼-- · 2019-01-17 23:17

Here are some different options:

  • You can use @Digits from bean validation.
  • You can use f:convertNumber.
  • You can validate the input in a backing bean method (you'll easily find tutorials for this)
  • If jsf 2.2 and html5 is an option for you, you can use <input type="number" />
  • Or you can use your own Javascript validation.

I think that the best options are either using Bean validation, f:convertNumber or going with HTML5 as these are the cleanest and give you the least redundant code.

查看更多
▲ chillily
5楼-- · 2019-01-17 23:17

Instead of PrimeFaces Extension for you can use now!

https://www.primefaces.org/showcase/ui/input/inputNumber.xhtml

查看更多
姐就是有狂的资本
6楼-- · 2019-01-17 23:20

Try

<h:inputText value="SomeValue" converter="javax.faces.Double" />
查看更多
Animai°情兽
7楼-- · 2019-01-17 23:22

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" />
查看更多
登录 后发表回答