我想在我的Managed 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:实例化org.hibernate.validator.engine.resolver.JPATraversableResolver的实例 . 信息:警告:FacesMessage已入队,但可能尚未显示 . sourceId = bRegForm:j_idt7 [severity =(ERROR 2),summary =(bRegForm:j_idt7:验证错误:值是必需的 . ),detail =(bRegForm:j_idt7:验证错误:值是必需的 . )]
可能是什么?我忘了什么吗?我是否必须在配置文件中添加内容...?
1 回答
您忘了给输入组件
id
. 这就是<h:message>
的for
属性所指向的位置 .与具体问题无关,你的方法是笨拙的,技术上是错误的 . 根据规范,你应该抛出ValidatorException . 而不是
做
然后,JSF将担心将组件设置为无效并将消息添加到上下文中 .
还有第二个问题,即您正在验证本地值而不是提交的值 .
更换
通过