JSF验证程序与字符串相等进行比较 [英] JSF Validator compare to Strings for Equality

查看:106
本文介绍了JSF验证程序与字符串相等进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您如何在JSF验证程序中比较两个字符串的相等性?

How would you compare two string for equality in a JSF Validator?

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

推荐答案

使用普通的Validator并将第一个组件的值作为第二个组件的属性传递.

Use a normal Validator and pass the value of first component as attribute of second component.

<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>展示柜上演示了确认密码"的确切情况.

If you happen to use JSF utility library OmniFaces, then you can use <o:validateEquals> for this. The exact case of "confirm password" is demonstrated on <o:validateEqual> showcase.

这篇关于JSF验证程序与字符串相等进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆