• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 580
  • 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

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

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