gpt4 book ai didi

jsf - 我如何验证两个组件的值是否相同? JSF

转载 作者:行者123 更新时间:2023-12-04 16:46:28 27 4
gpt4 key购买 nike

由于我们在 Asp.Net 中有 comparevalidator,我们在 JSF 中有什么来验证两个字段的值是否相同?我想验证密码和确认密码字段。

最佳答案

不,这样的验证器在基本的 JSF 实现中不存在。您基本上需要在组的 last 组件上运行验证器,并使用 UIViewRoot#findComponent() 获取您想要验证的 other 组件。 .例如

public void validate(FacesContext context, UIComponent component, Object value) {
UIComponent otherComponent = context.getViewRoot().findComponent("otherClientId");
Object otherValue = ((UIInput) otherComponent).getValue();
// ...
}

另见 this article了解更多背景信息和具体示例。

另一方面,如果您已经使用 JSF2,那么您也可以使用 ajaxical 验证:

<h:form>
<f:event type="postValidate" listener="#{bean.validate}" />
...
</h:form>

..这里 #{bean.validate}方法如下所示:

public void validate(ComponentSystemEvent e) {
UIComponent form = e.getComponent();
UIComponent oneComponent = form.findComponent("oneClientId");
UIComponent otherComponent = form.findComponent("otherClientId");
// ...
}

另见 this article获取更多 JSF2 验证示例。

如果您使用的是 JSF 实用程序库 OmniFaces , 那么你可以使用 <o:validateEqual> .它还允许设置自定义消息。 showcase有一个现场示例演示验证密码确认的常见用例。在调用验证器之前,您甚至不需要 ajax 来更新模型。

这是最少的必要代码:

<h:inputSecret id="password" value="#{signup.person.password}" />
<h:message for="password" />

<h:inputSecret id="confirmPassword" />
<h:message for="confirmPassword" />

<o:validateEqual components="password confirmPassword"
message="Passwords do not match!" showMessageFor="confirmPassword" />

无需额外的 Java 代码。

关于jsf - 我如何验证两个组件的值是否相同? JSF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2456272/

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