Struts的Validator驗證框架定義了常用的十幾個驗證規則,如:required(驗證非空)、minlength(驗證最小長度)、maxlength(驗證最大長度)、intRange(驗證整形範圍)、email(驗證電子郵件地址)、date(驗證日期)等,並且實現了客戶端的Javascript驗證和服務器端驗證,以下是在myeclipse環境下使用Validator驗證框架的步驟:
一、 創建基於Struts的web工程
二、 將validator-rules.xml中以下代碼拷貝到資源文件中
# Struts Validator Error Messages
errors.required={0} is required.
errors.minlength={0} can not be less than {1} characters.
errors.maxlength={0} can not be greater than {1} characters.
errors.invalid={0} is invalid.
errors.byte={0} must be a byte.
errors.short={0} must be a short.
errors.integer={0} must be an integer.
errors.long={0} must be a long.
errors.float={0} must be a float.
errors.double={0} must be a double.
errors.date={0} is not a date.
errors.range={0} is not in the range {1} through {2}.
errors.creditcard={0} is an invalid credit card number.
errors.email={0} is an invalid e-mail address.
三、將validator-rules.xml中以下代碼拷貝到struts-config.xml配置文件中,驗證框架將以插件形式被注入struts框架
<plug-in className="org.apache.struts.validator.ValidatorPlugIn"> <set-property property="pathnames" value="/WEB-INF/validator-rules.xml, /WEB-INF/validation.xml"/> </plug-in> |
四、創建validation.xml文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE form-validation PUBLIC "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0.1//EN" "validator_1_0_1.dtd" > <form-validation> <formset><!—配置特定於FormBean的驗證-à <form name="loginActionForm"> <!—name:屬性對應struts-config.xml中FormBean的名字-à <field property="login" depends="required"> <!—field:要驗證的字段,即屬性,depends:依賴的驗證規則à <arg0 key="loginActionForm.login"/> <!—arg0:在資源包中配置錯誤消息的{0}參數值à </field> <field property="password" depends="required,minlength"> <!—多個驗證規則用逗號分割à <arg0 key="loginActionForm.password"/> <arg1 key="#{var:minlength}" resource="false"/> <!—resource:false該key的值不在資源包中給出,而是在本文件給-à <var> <!—定義變量,給上面的key所用à <var-name>minlength</var-name> <var-value>6</var-value> </var> </field> </form> </formset> </form-validation>
|
五、實現客戶端的javascript驗證,只需在<form onSubmit=”return validateLonginActionForm(this);”>配置提交事件和使用<html:javascript formName=”loginActionForm”/>
<body> <font color="red"> <html:errors/> </font> //onSubmit=”return validate+formbean的名字” //<html:javascript formName=”formbean的名字”/> <html:form action="/login.do" onsubmit="return validateLoginActionForm(this);"> Login:<html:text property="login" /><br> Password:<html:text property="password" /><br> <html:submit/> </html:form> <html:javascript formName="loginActionForm"/> </body> |