gpt4 book ai didi

validation - JSF Validator 与字符串的平等比较

转载 作者:行者123 更新时间:2023-12-03 03:35:58 30 4
gpt4 key购买 nike

如何在 JSF 验证器中比较两个字符串是否相等?

if (!settingsBean.getNewPassword().equals(settingsBean.getConfirmPassword())) {
save = false;
FacesUtils.addErrorMessage(null, "Password and Confirm Password are not same", null);
}

最佳答案

使用正常的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="validateEqual" />
<f:attribute name="otherValue" value="#{passwordComponent.value}" />
</h:inputSecret>
<h:message for="confirmPassword" />

( note that binding on first component is exactly as-is; you shouldn't bind it to a bean property! )

@FacesValidator(value="validateEqual")
public class ValidateEqual implements Validator<Object> {

@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:validateEqual>为了这。 <o:validateEqual> showcase 演示了“确认密码”的具体情况。 .

另请参阅:

关于validation - JSF Validator 与字符串的平等比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5502506/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com