20
votes

Is there any inbuilt number validator tag in JSF that checks whether an input entered in h:inputext field is a number?

The first question was answered. Edited to explain the next problem:

<h:inputText id="maxrecs" value="#{simpleBean.numRecords}" required="false" maxlength="4" >                         
    <f:convertNumber longOnly="true"/>
</h:inputText>

Backing Bean

private long numRecords = null;

If I use String or Integer object in the backing bean , value is not being set. Now when I use primitive int, 0 is being printed on the screen. I would like the screen to be empty.

5

5 Answers

41
votes

You can use f:convertNumber (use the integerOnly attribute).

You can get more information here.

13
votes

You can use:

 <f:validateLongRange minimum="20" maximum="1000" />

Where minimum is the smallest number allowed and maximum is the largest. Look here for more details

7
votes

JSF Number validation for inputtext mention f:converterNumber component in between h inputText component and mention the attributes integerOnly and type.

<h:inputText id="textMobileId" label="Mobile" styleClass="controlfont" value="#{UserRegistrationBean.textMobile}">
    <f:convertNumber integerOnly="true" type="number" />
</h:inputText>

If you enter abcd in Mobile textbox at the time when you click on commandbutton it automatically shows an error like

Mobile: 'abcd' is not a number. 
3
votes

i8taken solution converts number into long without validation message (at least in my case: JSF2 / global messages per page). For proper validation message you can
1. check value in action method in bean;
or
2. use converter attribute for inputText:

<h:inputText id="maxrecs" value="#{simpleBean.numRecords}" maxlength="4" converter="javax.faces.Integer" />

-1
votes

You can simply use the passthrough, so first add this library

    xmlns:pt="http://xmlns.jcp.org/jsf/passthrough"

and after use this

   <h:inputText id="numberId" pt:type="number" />