codecamp

JSF 自定义验证错误消息示例

JSF教程 - JSF自定义验证错误消息示例


以下代码显示如何创建自定义验证消息。

例子

下面的代码来自UserBean.java。

package cn.w3cschool.common;

import java.io.Serializable;
import java.sql.Date;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
 
@ManagedBean(name="user")
@SessionScoped
public class UserBean implements Serializable{
  
  String username;
  Date dob;

  public String getUsername() {
    return username;
  }
  public void setUsername(String username) {
    this.username = username;
  }
  public Date getDob() {
    return dob;
  }
  public void setDob(Date dob) {
    this.dob = dob;
  }

}

以下代码来自demo.xhtml。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"   
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      >
    <h:body>
    <h:form>
      <h:panelGrid columns="3">
      
        Enter your username :
        
        <h:inputText id="username" value="#{user.username}" 
          size="20" required="true" label="Username">
          <f:validateLength minimum="5" maximum="10" />
        </h:inputText>
        
        <h:message for="username" style="color:red" />
        
        Enter your DOB :
        
        <h:inputText id="dob" value="#{user.dob}" 
          size="20" required="true" label="Date of Birth">
          <f:convertDateTime />
        </h:inputText>
        
        <h:message for="dob" style="color:red" />
        
      
      </h:panelGrid>
      
      <h:commandButton value="Submit" action="result" />
      
    </h:form>
    
    </h:body>
</html>

以下代码来自MyMessage.properties。

javax.faces.converter.DateTimeConverter.DATE={2}: ""{0}"" could not be understood as a date.
javax.faces.converter.DateTimeConverter.DATE_detail=Invalid date format.

javax.faces.validator.LengthValidator.MINIMUM=Minimum length of ""{0}"" is required.

以下代码来自result.xhtml。

?
下载 Custom-Validation-Error-Message.zip

运行

将生成的WAR文件从目标文件夹复制到Tomcat部署文件夹,并运行Tomcat-Install-folder/bin/startup.bat。

Tomcat完成启动后,在浏览器地址栏中键入以下URL。

http://localhost:8080/simple-webapp/demo.xhtml


JSF 验证正则表达式示例
JSF 自定义验证器示例
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }