Writing a custom validator in JSF 2 is not a complicated task. You implement Validator interface, add @FacesValidator annotation and insert validator declaration in faces-config.xml, that’s all. A piece of cake. But let’s consider following scenario:

You need custom date validator, let’s say checking that date from rich:calendar is not in the past. So we place calendar component with validator inside.

And our  validator could look like below:

And if we provide key value in properties file we will see something like this:

So it looks that we have working and production-ready custom validator.

The problem

But while our form becomes more and more complex we might encouter issue described on the screen below:

So the problem is how user can determine which date is valid and which is not? Our validator uses the same property key to display both error messages.

The solution

We need to somehow provide a label of validated field to our custom validator. And, ssurprisinglyfor JSF, it can be achieved pretty easily. The only catch is that you have to know how to do it 🙂

So in Java Server Faces we could parametrize components with attributes (f:attribute tag). So we add attribute to rich:calendar and then read this passed value value inside validator assigned to this calendar field. So now our calendar components should look like that:

And in our validator Java class we could get this value using uiComponent.getAttributes().get(“fieldLabel”);

Our property value for error should have value can not be in the past as Date or field label will be added at the beginning of error message.

And working example should show something similar to this screen: