问题
Validator Class:
@FacesValidator("br.gov.valec.sicpd.util.CpfValidator")
public class CpfValidator implements Validator {
@Override
public void validate(FacesContext context, UIComponent component, Object value)
throws ValidatorException {
if (validateCpf(value.toString())) {
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,"Invalid Input","Invalid Input");
((UIInput) component).setValid(false); // this line doesnt work
throw new ValidatorException(msg);
}
}
JSF snippet:
<p:inputText label="CPF" id="inputCpf"
value="#{mainBean.owner.cpf}">
<f:validator validatorId="br.gov.valec.sicpd.util.CpfValidator" />
<p:ajax event="change" update="inputNameOwner"
listener="#{mainBean.searchOwner}" />
</p:inputText>
When the form is submitted via command button primefaces highlights it automatically. How can I achieve that when ajax is fired and validation fails?
回答1:
The UIInput#setValid(false) is working fine. You just forgot to tell ajax to update the input component itself. Add inputCpf or @this to <p:ajax update>.
<p:ajax ... update="@this inputNameOwner" />
That explicit UIInput#setValid(false) call in validator is by the way unnecessary. Get rid of it. JSF already does it all by itself once it catches the ValidatorException thrown by your validator.
来源:https://stackoverflow.com/questions/18474140/how-can-i-highlight-uiinput-using-primefaces-when-validation-upon-ajax-request-f