gpt4 book ai didi

validation - 在自定义验证器中检查必填字段

转载 作者:行者123 更新时间:2023-12-04 05:14:24 25 4
gpt4 key购买 nike

我有一个自定义验证器设置为在复合组件的元素上运行。它看起来像这样:

<myproject:myComponent>
<f:validator validatorId="customValidator" for="validatedField" />
</myproject:myComponent>

复合组件如下所示:
<composite:interface>
<composite:editableValueHolder name="validatedField" targets="validatedField" />
</composite:interface>
<composite:implementation>
<h:inputText id="validatedField" />
</composite:implementation>

它主要工作,但有一个小问题:我如何根据需要指定一个字段?

看来,当我将验证字段完全留空时,根本不会调用自定义验证器。我尝试添加 <f:validateRequired for="validatedField" />mycomponent ,但它没有用。

编辑(响应 BalusC):我的复合组件的上下文的更详细描述出现在:
<p:outputPanel id="pnlElements">
<ui:repeat value="#{backingViewBean.elementDtos}" var="elementDto">
<p:commandButton value="Edit..."
action="#{backingControllerBean.refreshView}"
ajax="true"
update=":frmMain:editElement"
oncomplete="wdgEditElement.show()">
<f:setPropertyActionListener
target="#higherLevelControllerBean.currentElementId}"
value="#{elementDto.Id}" />
</p:commandButton>
</ui:repeat>
</p:outputPanel>

<p:dialog widgetVar="wdgEditElement" modal="true">
<p:outputPanel id="editElement">
<myproject:myComponent>
<f:validator validatorId="customValidator" for="validatedField" />
</myproject:myComponent>
</p:outputPanel>
</p:dialog>

该页面显示我创建的元素列表,每个元素都有一个编辑按钮(以及我省略的其他内容)。单击编辑按钮,会弹出一个包含复合组件的窗口(还有一个保存按钮,为了清楚起见再次省略),我可以在其中编辑元素。

问题是,当我设置 javax.faces.VALIDATE_EMPTY_FIELDS 时至 true ,验证器在填充编辑窗口的数据对象被设置之前被调用,它对我吠叫有空字段。 (并在数据对象设置之前中止执行,因此所有字段都显示为空。)

(此外,我注意到当 VALIDATE_EMPTY_FIELDS 设置为 false 时,我第二次和以后单击“编辑”按钮也会触发对验证器的调用。这看起来无害,但这不是我的行为期待。)

我在 Glassfish 下运行,所以我希望 <f:validateRequired>工作——所以也许我用错了。我是这样使用它的:
<myproject:myComponent>
<f:validator validatorId="customValidator" for="validatedField" />
<f:validateRequired for="validatedField" />
</myproject:myComponent>

我做错了吗?

最佳答案

<f:validateRequired>仅当在您的 Web 应用程序中启用 JSR303 bean 验证时才有效(在 Java EE Web 配置文件兼容服务器中通常是这种情况,例如 Glassfish、JBoss AS 和 TomEE,但在像 Tomcat 这样的简单 servletcontainer 中则不然)。如果您的 webapp 没有,那么您需要手动强制对空字段进行 bean 验证,如下所示 web.xml :

<context-param>
<param-name>javax.faces.VALIDATE_EMPTY_FIELDS</param-name>
<param-value>true</param-value>
</context-param>

关于validation - 在自定义验证器中检查必填字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14469952/

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