ITeye博客

JSF中的数据验证(1,前台验证 2,使用已有验证器 3,通过backing bean 4,自定义验证器)

zhoulei984623 · 2007-11-16 15:40 · Jsf · 正则表达式 · JSF · Bean · Markdown

1,

2,

3,通过backing bean进行验证

首先要在后台backing bean写相应的验证方法。

如下例子是为了验证输入数据是否是由数字和字母组成。
 

java 代码

 

  1. public void validateWord(FacesContext context, UIComponent toValidate, Object value) {  

         String word = (String) value;//得到输入的直  

         String reg = "^[A-Za-z0-9]+$";//根据验证要求写出相应正则表达式(各种验证表达式见本文最后)  

         PatternCompiler compiler = new Perl5Compiler();  

         Pattern pattern;  

         try {  

             pattern = compiler.compile(reg);  

      

         PatternMatcher matcher = new Perl5Matcher();  

         if(!matcher.contains(word, pattern)) {//判断是否匹配,如果不匹配输出相应错误信息  

             ((UIInput)toValidate).setValid(false);  

             FacesMessage message = new FacesMessage("Value accepts alphanumeric

                                     without space and symbols!");  

        //FacesMessage message = new FacesMessage("error message");     

        //context.addMessage(context.getViewRoot().findComponent("pForm:sizeLength")

          .getClientId(context),message);  

        //以上注释部分的意思是说将错误信息存储到页面id="pForm:sizeLength"的控件里而非当前控件  

             context.addMessage(toValidate.getClientId(context), message);  

         }  

         } catch (MalformedPatternException e) {  

             // TODO Auto-generated catch block  

             e.printStackTrace();  

         }  

     }

其次便是在页面调用该验证方法,例子如下:

JSF 代码

 

  1. <h:inputText value="#{containerListBean.container.assetCode}"
  2. validate="#{containerListBean.validateWord}" styleClass="inputTextBox">
  3. <h:message for="AssetCode" styleClass="errorMessage"></h:message>

OK了,其他的就不用说了。

4,自定义验证器



参开资料:正则表达式

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。