First of all, there is no "best" way. There's just the "right" way which depends on the concrete functional requirements.
The normal approach to validate in JSF is to use one of the standard validators available via <f:validateXxx>
tags, or to create a class which implements the Validator interface if the desired functionality is not available in the standard tags. An alternative would be to validate by JavaScript as you suggested yourself, but this completely defeats the robustness of server-side validation because JavaScript code is under full control by the enduser and thus editable/spoofable/disablable by the enduser.
In your particular case, you want to validate the input whether it matches a regular pattern. In that case, the <f:validateRegex>
is thus the right tag for the job.
As to the actual regular pattern, any number between 1 and 9 is in regex represented by [1-9]
and any alphabetic character between A and Z is in regex represented by [A-Z]
(case sensitive! if you intend to allow lowercase as well, use [a-zA-Z]
). Any "zero or one occurrence" like as the last number is in regex represented by (...)?
whereby the ...
is to be substituted with the actual pattern. The remainder, the characters /
and -
can be represented as-is as long as those are no special characters in regex such as .
, (
, etc, otherwise they needs to be escaped with \
.
So, all in all, this should do:
<h:inputText>
<f:validateRegex pattern="[1-9]/[A-Z]-[1-9]-[1-9]-[1-9](-[1-9])?" />
</h:inputText>
See also: