1

当用户输入非(DD-MON-YYYY)格式的日期时,我试图警告用户

我面临的问题是我使用 xml 验证来验证我的 jsp。当我用谷歌搜索它时,我们只检查 struts2 xml 验证中的日期范围。这是我的jsp。

<s:form action="capturePolicyPrgm">
    <s:div class="table">
        <s:textfield name="clientNo" label="CLIENT NUMBER" size="20"  />                    
        <s:textfield name="lifewardsCard" label="LIFE WARDS CARD NUMBER" size="20"/>                    
        <s:textfield name="policyCode" label="REFERRING POLICY NO" size="20"/>
        <s:select name="companyName" label="COMPANY"
            list="{'BIHL','BLIL','BIFM','LG','LEA'}" /> 
        <s:textfield name="doc" label="INCEPTION DATE" size="20"/>
        <s:select name="product" label="COVER ID"
            list="{'Card Holder','Spouse','Child 22-25 Yrs','Child 16-21 Yrs','Child 6-15 Yrs','Child 0-5(incl.Stillborn)'}" />             
        <s:textfield name="expiryDate" label="TERMINATION DATE" />
        <s:textfield name="premium" label="PREMIUM" />
        <tr>
            <td><s:submit value="submit" theme="simple" /></td>
            <td><s:submit type="button" theme="simple" onclick="clear();return false;"
                    value="clear" /></td>
        </tr>
    </s:div>
</s:form>

这是我的 xml 验证

<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
   "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">
 <validators>
  <field name="lifewardsCard">
    <field-validator type="requiredstring">
    <param name="minLength">16</param>
    <param name="maxLength">16</param>
        <message>Card number is required and must be of length 16</message>
    </field-validator>
</field>    
<field name="policyCode">
    <field-validator type="requiredstring">
        <message>Please enter referring Policy No.</message>
    </field-validator>
</field>
<field name="doc">
    <field-validator type="requiredstring">
        <message>Please Enter Policy Commencement Date.</message>
    </field-validator>
</field>    
<field name="expiryDate">
    <field-validator type="requiredstring">
        <message>Please Enter Policy Expiry Date.</message>
    </field-validator>
</field>

我的动作类正在实现模型驱动接口。请帮助我如何使用 xml 验证这一点。

4

1 回答 1

1

为什么不在 java 而不是 xml 中验证?

public static boolean isDateValid(String pDateToValidate, String pDateFormat)
{

    if (pDateToValidate == null)
    {
      return false;
    }

    SimpleDateFormat lSdf = new SimpleDateFormat(pDateFormat);
    lSdf.setLenient(false);

    try
    {

      // if not valid, it will throw ParseException
      Date lDate = lSdf.parse(pDateToValidate);
      System.out.println(lDate);
    }
    catch (ParseException e)
    {
      e.printStackTrace();
      return false;
    }

    return true;
}

public void validate()
{
    if (this.isDateValid(this.getExpiryDate(), "dd-MMM-yyyy") == false)
    {
      this.addFieldError("expiryDate", "Could not parse date, please enter in the format dd-MMM-yyyy.");
    }
}
于 2015-10-22T14:38:01.877 回答