我采用了以下BalusC 启动示例,并通过添加提交按钮和附加 h:messages 并f:ajax
从中h:inputSecret's
删除(由于某种原因删除了f:ajax
原因,当我离开第一个时h:inputSecret
,它立即显示“需要值”错误)第二h:inputSecret
- 但用户没有机会输入它...... ??? <- 另一个未来的问题?:))
好的,长话短说:
我试图弄清楚如何在全局 h:messages 中而不是在密码字段的单个 h:message 中显示关于两个密码字段(密码不相等)的验证错误我确实想要="true" 将显示在<h:message
每个字段的...
但是现在验证消息(由我的异常抛出)和 required="true" 显示在同一个地方
这是代码:
<h:outputLabel for="password" value="Password:" />
<h:inputSecret id="password" value="#{bean.password}" required="true">
<f:validator validatorId="confirmPasswordValidator" />
<f:attribute name="confirm" value="#{confirmPassword.submittedValue}" />
</h:inputSecret>
<h:message id="m_password" for="password" />
<h:outputLabel for="confirm" value="Password (again):" />
<h:inputSecret id="confirm" binding="#{confirmPassword}" required="true">
</h:inputSecret>
<h:message id="m_confirm" for="confirm" />
以及h:commandButton
下面h:messages
的代码:
<h:commandButton value="doSomething" action="#{myBean.myAction}">
<f:ajax execute="password confirm" render="m_password m_confirm"></f:ajax>
</h:commandButton>
<h:messages globalOnly="true" styleClass="validation_value_required"/>
@FacesValidator("confirmPasswordValidator")
public class ConfirmPasswordValidator implements Validator {
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
String password = (String) value;
String confirm = (String) component.getAttributes().get("confirm");
if (password == null || confirm == null) {
return; // Just ignore and let required="true" do its job.
}
if (!password.equals(confirm)) {
throw new ValidatorException(new FacesMessage("Passwords are not equal."));
}
}
}
还
提前谢谢,
解决方案(感谢 BalusC)
改变了
<f:attribute name="confirm" value="#{confirmPassword.submittedValue}" />
到
<f:attribute name="confirm" value="#{confirmPassword}" />
和
String confirm = (String) component.getAttributes().get("confirm");
进入
UIInput confirmPasswordComponent = (UIInput) component.getAttributes().get("confirm");
String confirm = (String) confirmPasswordComponent.getSubmittedValue();
和
throw new ValidatorException(new FacesMessage("Passwords are not equal."));
进入
context.addMessage(null, new FacesMessage("Passwords are not equal."));
context.validationFailed();
((UIInput) component).setValid(false);
confirmPasswordComponent.setValid(false);
return;