JSF表单验证失败后滚动到锚点或页面底部 [英] Scrolling to anchor or page bottom after JSF form validation fail
问题描述
我在页面底部有一个联系表单,其中包含必填字段和经过验证的表单字段.如果验证失败,如何使滚动位置回到页面底部?
I have a contact form at the bottom of a page with required and validated form fields. If validation fails, how can I get the scroll position back to the bottom of the page?
我希望此页面在禁用Java脚本的情况下工作,因此没有AJAX解决方案.我有这样的东西:
I want this page to work with Javascript disabled, so no AJAX solutions. I have something like this:
<a id="contact"></a>
<h:form id="cform">
<h5>Contact!</h5>
<h:outputLabel for="name">Name:
<h:message id="nameMsg" for="name" />
</h:outputLabel>
<h:inputText id="name" value="#{bean.name}" required="true" requiredMessage="Please enter name!" />
<h:outputLabel for="email">Email:
<h:message id="emailMsg" for="email" />
</h:outputLabel>
<h:inputText id="email" value="#{bean.email}" required="true" requiredMessage="Email is required!">
<f:validator validatorId="myValidator" />
</h:inputText>
<h:outputLabel for="comment">Comment:
<h:message id="commentMsg" for="comment" />
</h:outputLabel>
<h:inputTextarea id="comment" value="#{bean.comment}" required="true" requiredMessage="Please enter a comment!"/>
<h:commandButton action="#{bean.go}" id="send" value="send" />
</h:form>
我考虑过在Bean端进行验证并手动重定向到适当的锚点,但这似乎违背了使用JSF的目的.我认为有一个简单的方法可以做到这一点,但是我在Google搜索解决方案时遇到了麻烦,因为我可能说的不是正确的问题.有人吗?
I thought about doing validations on the bean side and doing manual redirects to the appropriate anchor, but that seems to defeat the purpose of using JSF to begin with. I assume there is an easy way to do this, but I'm having trouble Googling a solution because I'm probably not wording the question right. Any one?
推荐答案
您可以使用 以在验证阶段之后立即具有侦听器挂钩.您可以使用 FacesContext#isValidationFailed()
检查验证是否失败.您可以使用 Flash#setKeepMessages()
,以便让面孔消息在重定向中幸存(默认情况下,它们是作用域要求的!).您可以使用 ExternalContext#redirect()
以非操作方法执行重定向.
You can use <f:event type="postValidate">
to have a listener hook right after the validations phase. You can use FacesContext#isValidationFailed()
to check if validation has failed or not. You can use Flash#setKeepMessages()
to let the faces messages survive a redirect (they're namely by default request scoped!). You can use ExternalContext#redirect()
to perform a redirect in a non-action method.
因此,总结起来,这应该做到:
So, summarized, this should do:
<h:form id="cform">
...
<f:event type="postValidate" listener="#{bean.postValidate}" />
</h:form>
具有:
public void postValidate() throws IOException {
FacesContext context = FacesContext.getCurrentInstance();
if (context.isValidationFailed()) {
context.getExternalContext().getFlash().setKeepMessages(true);
context.getExternalContext().redirect("contact.xhtml#cform");
}
}
这篇关于JSF表单验证失败后滚动到锚点或页面底部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!