您可以自訂自己的驗證器,所需要的是實作javax.faces.validator.Validator介面,例如我們實作一個簡單的密碼驗證器,檢查字元長度,以及密碼中是否包括字元與數字:
package onlyfun.caterpillar;
import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.validator.Validator; import javax.faces.validator.ValidatorException;
public class PasswordValidator implements Validator { public void validate(FacesContext context, UIComponent component, Object obj) throws ValidatorException { String password = (String) obj; if(password.length() < 6) { FacesMessage message = new FacesMessage( FacesMessage.SEVERITY_ERROR, "字元長度小於6", "字元長度不得小於6"); throw new ValidatorException(message); } if(!password.matches(".+[0-9]+")) { FacesMessage message = new FacesMessage( FacesMessage.SEVERITY_ERROR, "密碼必須包括字元與數字", "密碼必須是字元加數字所組成"); throw new ValidatorException(message); } } }
您要實作javax.faces.validator.Validator介面中的validate()方法,如果驗證錯誤,則丟出一個
ValidatorException,它接受一個FacesMessage物件,這個物件接受三個參數,分別表示訊息的嚴重程度(INFO、
WARN、ERROR、FATAL)、訊息概述與詳細訊息內容,這些訊息將可以使用<h:messages>或<h:
message>標籤顯示在頁面上。
接下來要在faces-config.xml中註冊驗證器的識別(Validater ID),要加入以下的內容:
<?xml version="1.0"?> <!DOCTYPE faces-config PUBLIC "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN" "http://java.sun.com/dtd/web-facesconfig_1_0.dtd">
<faces-config> .... <validator> <validator-id> onlyfun.caterpillar.Password </validator-id> <validator-class> onlyfun.caterpillar.PasswordValidator </validator-class> </validator> .... </faces-config>
要使用自訂的驗證器,我們可以使用<f:validator>標籤並設定validatorId屬性,例如:
....
<h:inputSecret value="#{user.password}" required="true">
<f:validator validatorId="onlyfun.caterpillar.Password"/>
</h:inputSecret><p>
....
您也可以讓Bean自行負責驗證的工作,可以在Bean上提供一個驗證方法,這個方法沒有傳回值,並可以接收FacesContext、 UIComponent、Object三個參數,例如:
package onlyfun.caterpillar;
import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.validator.ValidatorException;
public class UserBean { .... public void validate(FacesContext context, UIComponent component, Object obj) throws ValidatorException { String password = (String) obj; if(password.length() < 6) { FacesMessage message = new FacesMessage( FacesMessage.SEVERITY_ERROR, "字元長度小於6", "字元長度不得小於6"); throw new ValidatorException(message); } if(!password.matches(".+[0-9]+")) { FacesMessage message = new FacesMessage( FacesMessage.SEVERITY_ERROR, "密碼必須包括字元與數字", "密碼必須是字元加數字所組成"); throw new ValidatorException(message); } } }
接著可以在頁面下如下使用驗證器:
.....
<h:inputSecret value="#{user.password}"
required="true"
validator="#{user.validate}"/>
....
|