Parametrizing Custom Validator in JSF 2
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.
1 2 3
And our validator could look like below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
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.
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.
We need to somehow provide a label of validated field to our custom validator. And, suprisingly for 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:
1 2 3 4
And in our validator Java class we could get this value using uiComponent.getAttributes().get(“fieldLabel”);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
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: