I need to validate across multiple fields in such a way that validation should be violated only when one of the given fields is violated.
It is distinct from cross field validation in which a value of one field is dependent upon the value(s) of one or more of the rest of the fields.
Given below a simple scenario.
<p:inputText id="txt1" value="#{testBean.txt1}" required="false" maxlength="45"/>
<p:inputText id="txt2" value="#{testBean.txt2}" required="false" maxlength="45"/>
<p:inputText id="txt3" value="#{testBean.txt3}" required="false" maxlength="45"/>
<p:commandButton id="btnSubmit" actionListener="#{testBean.insert}"
icon="ui-icon-check" value="Save"/>
In which, validation violation should be occurred only when one of the given three text fields is left blank. If anyone of them is filled with a value then, all should be validated. In which case, validation should not be violated.
How to proceed with this scenario? Does JSF/PrimeFaces provide some way to perform validation in this way?
I have a hard time in wrapping my head around your concrete functional requirement, but I believe you're looking for "all or none" validation. I.e. either all fields should be blank, or all fields should be filled. JSF utility library OmniFaces has a validator for exactly this purpose, the
<o:validateAllOrNone>
.Here's how you could use it:
Of course!
Primefaces provide a lot of ways that can satisfact you. First of all, you can make validations in your MBean method. In your case, you're calling
insert
method, so you can do something like this:Note that you can improve the validations by yourself, following your needs. You can also change the message from:
to:
What can give your application a better error message.
Before this works, add this above your input fields:
Probably this will work like a charm! If you're interested, check the Primefaces Messages showcase, where you can find some examples and understand better how
<p:messages>
works.Also, feel free to check
<p:growl>
, that in my opinion is a lot better than simple messages. Check out the growl here.Hope I helped you (: