问题
i have a requirement where a input field which takes strings can have only one of these formats, what is the best way to implement this using javascript or jsf validator:
N/A-N-N-N or N/A-N-N-N-N
There can be any alphabet in pattern above in place of A. there can be any numeric in pattern above in place of N other than 0.
回答1:
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:
- Regex tutorial
- java.util.regex.Pattern javadoc
回答2:
Use following expression if you are allowing to enter either uppercase or lowercase characters.
<h:inputText>
<f:validateRegex pattern="[1-9]/[a-zA-Z](-[1-9]){3,4}" />
</h:inputText>
回答3:
<h:inputText>
<f:validateRegex pattern="((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})" />
</h:inputText>
from this pattern, it is accepted only if it is in range of 6 to 20 with at least one digit, one upper case letter, one lower case letter and one special symbol (“@#$%”)
来源:https://stackoverflow.com/questions/19161040/how-to-validate-string-input-field-for-pattern-on-jsf-form