Skip to main content

JSF Tip #5 - The DoubleRangeValidator

Posted by mriem on September 5, 2012 at 2:49 PM PDT

Just like the LongRangeValidator before the DoubleRangeValidator validates if the given value is within the given range, but then a range of doubles.

Say you want to make sure your donors can donate as little as 1.00 but at most 250.00.

 <html xmlns:h="http://java.sun.com/jsf/html"  xmlns:f="http://java.sun.com/jsf/core">
  <h:inputText value="#{donation.amount}">
   <f:validateDoubleRange minimum="1.00" maximum="250.00" />
  </h:inputText>
</html>

The minimum and maximum values mentioned above do not have fixed values, you can use an EL expression if you have different range requirements for different usage patterns. Note the minimum and maximum values need to evaluate to a Double. Eg.

 <html xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core">
  <h:inputText value="#{donation.amount}">
   <f:validateDoubleRange minimum="#{settings.minimumDonatioon}" maximum="#{settings.maximumDonation}" />
  </h:inputText>
</html>

If you want to disable the DoubleRangeValidator on a page your can mark the validator as disabled as follows:

 <html xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core">
  <h:inputText value="#{donation.amount}">
   <f:validateDoubleRange disabled="true" minimum="1.00" maximum="250.00" />
  </h:inputText>
</html>

If you keep an instance of a DoubleRangeValidator around in your managed bean you can also use binding to bind that particular instance of the DoubleRangeValidator to the tag on the page like so:

 <html xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core">
  <h:inputText value="#{donation.amount}">
   <f:validateDoubleRange binding="#{settings.doubleRangeValidator}" />
  </h:inputText>
</html>

And a managed bean that has a method similar to the one below:

 public DoubleRangeValidator getDoubleRangeValidator() {
  return doubleRangeValidator;
}

If you specifically want to attach the validator to a specific component then you can use the 'for' attribute to target it. Note this attribute is really helpful when using composite components. Eg.

 <html xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core">
  <h:inputText id="myinput" value="#{donation.amount}">
   <f:validateDoubleRange binding="#{settings.doubleRangeValidator}" for="myinput"/>
  </h:inputText>
</html>
Related Topics >>