I understand I cannot use <c:choose>
within a component in a jsf page. I am trying to see if there is an alternative. I looked at the Tomahawk and that isn't what I really need. I am trying to validate negative and positive numbers in a column. I want to be able to choose between the 2 validator tags that I have created. I tried using the rendered attribute but it still doesn't work. Below is kind of what I am looking for but it is not working like I want it to. Does anyone have any suggestions??
Thanks in advance.
<c:choose>
<c:when test="#{entry.dataEntry.posValue}">
<f:validator validatorId="hits.positiveNumberValidator"/>
</c:when>
<c:otherwise test="#{entry.dataEntry.开发者_如何学JAVAnegValue}">
<f:validator validatorId="hits.negativeNumberValidator"/>
</c:otherwise>
</c:choose>
Wrap in another validator and add them as attributes.
<f:validator validatorId="hits.numberValidator"/>
<f:attribute name="posValue" value="#{entry.dataEntry.posValue}" />
<f:attribute name="negValue" value="#{entry.dataEntry.negValue}" />
And then in the NumberValidator
:
Boolean negValue = component.getAttributes().get("negValue");
if (posValue != null && posValue) {
new PositiveNumberValidator().validate(context, component, value);
}
Boolean posValue = component.getAttributes().get("posValue");
if (negValue != null && negValue) {
new NegativeNumberValidator().validate(context, component, value);
}
Note that this doesn't work when #{entry}
is actually an iterated item like as declared in var
attribute of h:dataTable
or ui:repeat
, because the f:attribute
is tied to the JSF component, not to its output. Since the variable name #{entry}
hints less or more that this is actually the case, here's how you could do it.
Wrap the collection in a DataModel
:
private DataModel entries;
public Bean() {
entries = new ListDataModel(someDAO.list());
}
// ...
Use it in h:dataTable
or ui:repeat
as follows:
<h:dataTable value="#{bean.entries}" var="entry">
<h:column>
<h:inputText validator="#{bean.numberValidator}" />
</h:column>
</h:dataTable>
And implement the validator in the Bean
as follows:
public void numberValidator(FacesContext context, UIComponent component, Object value) throws ValidatorException) {
Entry entry = (Entry) entries.getRowData();
if (entry.isPosValue()) {
new PositiveNumberValidator().validate(context, component, value);
}
if (entry.isNegValue()) {
new NegativeNumberValidator().validate(context, component, value);
}
}
(you may want to make those validators an instance variable of the bean instead (only if they are threadsafe))
精彩评论