[Last Call] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 577
  • Last Modified:

Avaoiding fractional numbers in JSF

I have a JSF form where i will be providing values in the text boxes. The text box should accept only Whole numbers. It should not accept non-numeric values like alphabets, special characters and also it should not accept "fractions". Only positive numbers should be allowed.

how this can be done?
1 Solution
Does this help you?


They add a Integer Only Validator to the desired Field.
You can use a bean to do that.This is what we did
The example is for phone number but you can use the same for whole numbers
 <t:inputText id="daytimePhone" value="#{customer.daytimePhone}"        required="true" forceId="true">
                   <t:message style="color:red" for="daytimePhone" />
                    <f:validator validatorId="phoneNumberValidator"/>
In the faces config file
This is the bean
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class PhoneNumberValidator implements Validator
    private static final Log log = LogFactory.getLog(PhoneNumberValidator.class);
    private static final String PHONE_NUMBER_PATTERN = "[0-9]{3}[-]{1}[0-9]{3}[-]{1}[0-9]{4}";
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException
        /* create a mask*/
        Pattern mask = Pattern.compile(PHONE_NUMBER_PATTERN);
        /* retrieve the string value of the field*/
        String phoneNumber = (String)value;
        /*check to ensure that the value is a phone number*/
        Matcher matcher = mask.matcher(phoneNumber);
            FacesMessage message = new FacesMessage();
            message.setDetail("Phone number not in valid format");
            message.setSummary("Phone number not in valid format");
            throw new ValidatorException(message);

Open in new window


Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now