Skip to main content

JSF Tip #4 - The LongRangeValidator

Posted by mriem on September 5, 2012 at 5:02 AM PDT

If you want to make sure a value is within given Long range then the LongRangeValidator is for you!

Say you want to make sure your users are at least 13 but at most 18.

 <html xmlns:h="http://java.sun.com/jsf/html"  xmlns:f="http://java.sun.com/jsf/core">
  <h:inputText value="#{user.age}">
   <f:validateLongRange minimum="13" maximum="18" />
  </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 Long. Eg.

 <html xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core">
  <h:inputText value="#{user.age}">
   <f:validateLongRange minimum="#{settings.minimumAge}" maximum="#{settings.maximumAge}" />
  </h:inputText>
</html>

If you want to disable the LongRangeValidator 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="#{user.age}">
   <f:validateLongRange disabled="true" minimum="6" maximum="12" />
  </h:inputText>
</html>

If you keep an instance of a LongRangeValidator around in your managed bean you can also use binding to bind that particular instance of the LongRangeValidator 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="#{user.age}">
   <f:validateLongRange binding="#{settings.longRangeValidator}" />
  </h:inputText>
</html>

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

 public LongRangeValidator getLongRangeValidator() {
  return longRangeValidator;
}

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="#{user.age}">
   <f:validateLongRange binding="#{settings.longRangeValidator}" for="myinput"/>
  </h:inputText>
</html>