gpt4 book ai didi

java - JSF 2.0 自定义验证问题

转载 作者:行者123 更新时间:2023-11-30 07:34:24 25 4
gpt4 key购买 nike

我想在我的托管 bean 中验证对我的 JSF 页面的输入,但由于某种原因它不起作用?

@ManagedBean
@RequestScoped
public class RegistrationController {
//values passed from the JSF page
private String name;
...
public void validateName(FacesContext context, UIComponent validate,
Object value) {
String inputFromField = (String) value;
String simpleTextPatternText = "^[a-zA-Z0-9]+$";
Pattern textPattern = null;
Matcher nameMatcher = null;
textPattern = Pattern.compile(simpleTextPatternText);
nameMatcher = textPattern.matcher(getName());

if (!nameMatcher.matches()) {
((UIInput) validate).setValid(false);
FacesMessage msg = new FacesMessage(
"your name cant contain special characters");
context.addMessage(validate.getClientId(), msg);
}
}

这是输入组件的样子(在表单内):

<h:inputText value="#{registrationController.name}" validator="#{registrationController.validateName}" required="true">
<h:message for="nameInput"/>

当我输入错误时,我看不到验证消息,但在控制台中我看到了:

INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver. INFO: WARNING: FacesMessage(s) have been enqueued, but may not have been displayed. sourceId=bRegForm:j_idt7[severity=(ERROR 2), summary=(bRegForm:j_idt7: Validation Error: Value is required.), detail=(bRegForm:j_idt7: Validation Error: Value is required.)]

它可能是什么?我忘记了什么吗?我是否必须向我的配置文件中添加一些内容...?

最佳答案

你忘了给你的输入组件一个 id .那就是 for 的地方<h:message> 的属性应该指向。

<h:inputText id="nameInput">

与具体问题无关,您的方法笨拙且技术上错误。根据规范,您应该抛出 ValidatorException .所以不是

((UIInput) validate).setValid(false);
context.addMessage(validate.getClientId(), msg);

throw new ValidatorException(msg);

然后 JSF 会担心将组件设置为无效并将消息添加到上下文。


还有第二个问题,您正在验证本地值而不是提交的值。

替换

nameMatcher = textPattern.matcher(getName());

通过

nameMatcher = textPattern.matcher(inputFromField);

关于java - JSF 2.0 自定义验证问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5196044/

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