Skip to main content

JSF Tip #3 - The LengthValidator

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

The LengthValidator is one of the standard validators that is specified by the JavaServerFaces specification. It allows you to verify (validate) if the proposed input (submitted value) on a given component is valid.

Say you want to make sure the minimum length of a password is 6 characters and up to 12 characters. The example below describe how you would put this into a JSF page to make that validation happen.

<html xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core">
<h:inputText value="#{user.password}">
  <f:validateLength minimum="6" maximum="12" />
</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 length requirements for different usage patterns. Eg.

<html xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core">
<h:inputText value="#{address.zipCode}">
  <f:validateLength minimum="#{settings.zipCodeMinimum}" maximum="#{settings.zipCodeMaximum}" />
</h:inputText>
</html>

If you want to disable the LengthValidator 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.password}">
  <f:validateLength disabled="true" minimum="6" maximum="12" />
</h:inputText>
</html>

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

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

   public LengthValidator getLengthValidator() {
     return lengthValidator;
   }

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.password}">
  <f:validateLength binding="#{settings.lengthValidator}" for="myinput"/>
</h:inputText>
</html>