使用正常Validator
並通過第一分量的值作爲第二成分的屬性。
<h:inputSecret id="password" binding="#{passwordComponent}" value="#{bean.password}" required="true"
requiredMessage="Please enter password" validatorMessage="Please enter at least 8 characters">
<f:validateLength minimum="8" />
</h:inputSecret>
<h:message for="password" />
<h:inputSecret id="confirmPassword" required="#{not empty passwordComponent.value}"
requiredMessage="Please confirm password" validatorMessage="Passwords are not equal">
<f:validator validatorId="equalsValidator" />
<f:attribute name="otherValue" value="#{passwordComponent.value}" />
</h:inputSecret>
<h:message for="confirmPassword" />
(note that binding
in above example is as-is; you shouldn't bind it to a bean property!)
與
@FacesValidator(value="equalsValidator")
public class EqualsValidator implements Validator {
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
Object otherValue = component.getAttributes().get("otherValue");
if (value == null || otherValue == null) {
return; // Let required="true" handle.
}
if (!value.equals(otherValue)) {
throw new ValidatorException(new FacesMessage("Values are not equal."));
}
}
}
如果你碰巧使用JSF工具庫OmniFaces,那麼你可以使用<o:validateEquals>
這一點。在<o:validateEqual>
showcase上顯示「確認密碼」的確切情況。
嗨BalusC,有沒有其他的方式來做到這一點,而無需綁定inputSecret組件? – c12 2011-04-03 02:58:25
您可以對ID進行硬編碼並將其傳遞給它。例如。 ' '然後使用'UIViewRoot#findComponent()'獲取組件。然而這只是笨拙的。爲什麼反對約束?這對我沒有意義。 –
BalusC
2011-04-03 02:59:29
當爲組件添加綁定時,沒有額外的開銷(內存明智)嗎?它可能很小,但只是一個問題。 – c12 2011-04-03 06:35:54