Chinaunix首页 | 论坛 | 博客
  • 博客访问: 342558
  • 博文数量: 329
  • 博客积分: 2633
  • 博客等级: 少校
  • 技术积分: 3633
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-22 15:43
文章分类

全部博文(329)

文章存档

2013年(244)

2012年(46)

2011年(39)

我的朋友

分类: 系统运维

2012-03-21 12:29:58

摘自精通struts
validator.xml:

点击(此处)折叠或打开

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE form-validation PUBLIC "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0//EN" "validator_1_0.dtd" >
  3. <form-validation>
  4.     <global>
  5.         <constant>
  6.             <constant-name>numericchar</constant-name>
  7.             <constant-value>^\w+$</constant-value>
  8.         </constant>
  9.     </global>

  10.     <formset>
  11.         <form name="CheckForm">
  12.             <field property="userName" depends="required,mask">
  13.                 <arg0 key="userName" />
  14.                 <var>
  15.                     <var-name>mask</var-name>
  16.                     <var-value>${numericchar}</var-value>
  17.                 </var>
  18.             </field>
  19.             
  20.             <!-- <field property="passWord" depends="minlength,maxlength,required,mask">-->
  21.             <field property="passWord" depends="required,mask,minmaxlength">
  22.                 <arg0 key="passWord" ></arg0>
  23.                 <arg1 key="6" resource="false"></arg1>
  24.                 <arg2 key="12" resource="false"></arg2>
  25.                 <var>
  26.                     <var-name>mask</var-name>
  27.                     <var-value>${numericchar}</var-value>
  28.                 </var>
  29.                 <var>
  30.                     <var-name>maxlength</var-name>
  31.                     <var-value>12</var-value>
  32.                 </var>
  33.                 <var>
  34.                     <var-name>minlength</var-name>
  35.                     <var-value>6</var-value>
  36.                 </var>
  37.             </field>
  38.             <field property="age" depends="range">
  39.                 <arg0 key="age" />
  40.                 <arg1 key="18" resource="false" />
  41.                 <arg2 key="30" resource="false" />
  42.                 <var>
  43.                     <var-name>min</var-name>
  44.                     <var-value>18</var-value>
  45.                 </var>
  46.                 <var>
  47.                     <var-name>max</var-name>
  48.                     <var-value>30</var-value>
  49.                 </var>
  50.             </field>
  51.             <field property="email" depends="email">
  52.                 <arg0 key="email"></arg0>
  53.             </field>
  54.         </form>
  55.     </formset>
  56. </form-validation>
 
NewValidator.java:(自定义校验类)
 

点击(此处)折叠或打开

  1. package struts.sample.cap5.sample1.validator;
  2. import java.io.Serializable;

  3. import javax.servlet.http.HttpServletRequest;

  4. import org.apache.commons.validator.Field;
  5. import org.apache.commons.validator.ValidatorAction;
  6. import org.apache.commons.validator.ValidatorUtil;
  7. import org.apache.struts.action.ActionErrors;
  8. import org.apache.struts.util.StrutsValidatorUtil;

  9. public class NewValidator implements Serializable {

  10.     public static boolean validateMinMaxLength(Object bean, ValidatorAction va,
  11.             Field field, ActionErrors errors, HttpServletRequest request) {

  12.         String value = null;
  13.         // 将检验的字段转为String

  14.         if (field.getProperty() != null && field.getProperty().length() > 0) {
  15.             value = ValidatorUtil.getValueAsString(bean, field.getProperty());
  16.         }
  17.         //从var元素得到校验参数

  18.         String sMaxLength = field.getVarValue("maxlength");
  19.         String sMinLength = field.getVarValue("minlength");

  20.         //当校验的字段不为空时进行校验

  21.         if (value != null) {
  22.             try {
  23.                 int valueLength = value.length();
  24.                 int maxLength = Integer.parseInt(sMaxLength);
  25.                 int minLength = Integer.parseInt(sMinLength);

  26.                 //若字段的字符数大于校验参数maxlength或小于校验参数minLength时将返回报错信息

  27.                 if (valueLength > maxLength || valueLength < minLength) {
  28.                     errors.add(field.getKey(), StrutsValidatorUtil
  29.                             .getActionError(request, va, field));
  30.                     return false;
  31.                 }
  32.             } catch (Exception e) {
  33.                 //当捕捉到任何异常时将返回报错信息

  34.                 errors.add(field.getKey(), StrutsValidatorUtil.getActionError(
  35.                         request, va, field));
  36.                 return false;
  37.             }
  38.         }
  39.         return errors.empty();
  40.     }
  41. }

validator-rules.xml:

点击(此处)折叠或打开

  1. <!DOCTYPE form-validation PUBLIC
  2.           "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0//EN"
  3.           "">
  4. <!--

  5.    This file contains the default Struts Validator pluggable validator
  6.    definitions. It should be placed somewhere under /WEB-INF and
  7.    referenced in the struts-config.xml under the plug-in element
  8.    for the ValidatorPlugIn.

  9.       <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
  10.         <set-property property="pathnames" value="/WEB-INF/validator-rules.xml,
  11.                                                   /WEB-INF/validation.xml"/>
  12.       </plug-in>

  13.    These are the default error messages associated with
  14.    each validator defined in this file. They should be
  15.    added to your projects ApplicationResources.properties
  16.    file or you can associate new ones by modifying the
  17.    pluggable validators msg attributes in this file.

  18.    # Struts Validator Error Messages
  19.    errors.required={0} is required.
  20.    errors.minlength={0} can not be less than {1} characters.
  21.    errors.maxlength={0} can not be greater than {1} characters.
  22.    errors.invalid={0} is invalid.

  23.    errors.byte={0} must be a byte.
  24.    errors.short={0} must be a short.
  25.    errors.integer={0} must be an integer.
  26.    errors.long={0} must be a long.
  27.    errors.float={0} must be a float.
  28.    errors.double={0} must be a double.

  29.    errors.date={0} is not a date.
  30.    errors.range={0} is not in the range {1} through {2}.
  31.    errors.creditcard={0} is an invalid credit card number.
  32.    errors.email={0} is an invalid e-mail address.

  33. -->

  34. <form-validation>

  35.    <global>

  36.       <validator name="required"
  37.             classname="org.apache.struts.validator.FieldChecks"
  38.                method="validateRequired"
  39.          methodParams="java.lang.Object,
  40.                        org.apache.commons.validator.ValidatorAction,
  41.                        org.apache.commons.validator.Field,
  42.                        org.apache.struts.action.ActionErrors,
  43.                        javax.servlet.http.HttpServletRequest"
  44.                   msg="errors.required">

  45.          <javascript><![CDATA[
  46.             function validateRequired(form) {
  47.                 var isValid = true;
  48.                 var focusField = null;
  49.                 var i = 0;
  50.                 var fields = new Array();
  51.                 oRequired = new required();
  52.                 for (x in oRequired) {
  53.                     var field = form[oRequired[x][0]];
  54.                     
  55.                     if (field.type == 'text' ||
  56.                         field.type == 'textarea' ||
  57.                         field.type == 'file' ||
  58.                         field.type == 'select-one' ||
  59.                         field.type == 'radio' ||
  60.                         field.type == 'password') {
  61.                         
  62.                         var value = '';
  63.                         // get field's value
  64.                         if (field.type == "select-one") {
  65.                             var si = field.selectedIndex;
  66.                             if (si >= 0) {
  67.                                 value = field.options[si].value;
  68.                             }
  69.                         } else {
  70.                             value = field.value;
  71.                         }
  72.                         
  73.                         if (trim(value).length == 0) {
  74.                         
  75.      if (i == 0) {
  76.      focusField = field;
  77.      }
  78.      fields[i++] = oRequired[x][1];
  79.      isValid = false;
  80.                         }
  81.                     }
  82.                 }
  83.                 if (fields.length > 0) {
  84.                    focusField.focus();
  85.                    alert(fields.join('\n'));
  86.                 }
  87.                 return isValid;
  88.             }
  89.             
  90.             // Trim whitespace from left and right sides of s.
  91.             function trim(s) {
  92.                 return s.replace( /^\s*/, "" ).replace( /\s*$/, "" );
  93.             }
  94.             
  95.             ]]>
  96.          

  97.       

  98.       
  99.                  classname="org.apache.struts.validator.FieldChecks"
  100.                  method="validateRequiredIf"
  101.                  methodParams="java.lang.Object,
  102.                                org.apache.commons.validator.ValidatorAction,
  103.                                org.apache.commons.validator.Field,
  104.                                org.apache.struts.action.ActionErrors,
  105.                                org.apache.commons.validator.Validator,
  106.                                javax.servlet.http.HttpServletRequest"
  107.                  msg="errors.required">
  108.       

  109.       
  110.             classname="org.apache.struts.validator.FieldChecks"
  111.                method="validateMinLength"
  112.          methodParams="java.lang.Object,
  113.                        org.apache.commons.validator.ValidatorAction,
  114.                        org.apache.commons.validator.Field,
  115.                        org.apache.struts.action.ActionErrors,
  116.                        javax.servlet.http.HttpServletRequest"
  117.               depends=""
  118.                   msg="errors.minlength">

  119.          
  120.             function validateMinLength(form) {
  121.                 var isValid = true;
  122.                 var focusField = null;
  123.                 var i = 0;
  124.                 var fields = new Array();
  125.                 oMinLength = new minlength();
  126.                 for (x in oMinLength) {
  127.                     var field = form[oMinLength[x][0]];
  128.                     
  129.                     if (field.type == 'text' ||
  130.                         field.type == 'textarea') {
  131.                         
  132.                         var iMin = parseInt(oMinLength[x][2]("minlength"));
  133.                         if ((trim(field.value).length > 0) && (field.value.length < iMin)) {
  134.                             if (i == 0) {
  135.                                 focusField = field;
  136.                             }
  137.                             fields[i++] = oMinLength[x][1];
  138.                             isValid = false;
  139.                         }
  140.                     }
  141.                 }
  142.                 if (fields.length > 0) {
  143.                    focusField.focus();
  144.                    alert(fields.join('\n'));
  145.                 }
  146.                 return isValid;
  147.             }]]>
  148.          

  149.       


  150.       
  151.             classname="org.apache.struts.validator.FieldChecks"
  152.                method="validateMaxLength"
  153.          methodParams="java.lang.Object,
  154.                        org.apache.commons.validator.ValidatorAction,
  155.                        org.apache.commons.validator.Field,
  156.                        org.apache.struts.action.ActionErrors,
  157.                        javax.servlet.http.HttpServletRequest"
  158.               depends=""
  159.                   msg="errors.maxlength">

  160.          
  161.             function validateMaxLength(form) {
  162.                 var isValid = true;
  163.                 var focusField = null;
  164.                 var i = 0;
  165.                 var fields = new Array();
  166.                 oMaxLength = new maxlength();
  167.                 for (x in oMaxLength) {
  168.                     var field = form[oMaxLength[x][0]];
  169.                     
  170.                     if (field.type == 'text' ||
  171.                         field.type == 'textarea') {
  172.                         
  173.                         var iMax = parseInt(oMaxLength[x][2]("maxlength"));
  174.                         if (field.value.length > iMax) {
  175.                             if (i == 0) {
  176.                                 focusField = field;
  177.                             }
  178.                             fields[i++] = oMaxLength[x][1];
  179.                             isValid = false;
  180.                         }
  181.                     }
  182.                 }
  183.                 if (fields.length > 0) {
  184.                    focusField.focus();
  185.                    alert(fields.join('\n'));
  186.                 }
  187.                 return isValid;
  188.             }]]>
  189.          

  190.       


  191.       
  192.             classname="org.apache.struts.validator.FieldChecks"
  193.                method="validateMask"
  194.          methodParams="java.lang.Object,
  195.                        org.apache.commons.validator.ValidatorAction,
  196.                        org.apache.commons.validator.Field,
  197.                        org.apache.struts.action.ActionErrors,
  198.                        javax.servlet.http.HttpServletRequest"
  199.               depends=""
  200.                   msg="errors.invalid">

  201.          
  202.             function validateMask(form) {
  203.                 var isValid = true;
  204.                 var focusField = null;
  205.                 var i = 0;
  206.                 var fields = new Array();
  207.                 oMasked = new mask();
  208.                 for (x in oMasked) {
  209.                     var field = form[oMasked[x][0]];
  210.                     
  211.                     if ((field.type == 'text' ||
  212.                          field.type == 'textarea') &&
  213.                          (field.value.length > 0)) {
  214.                         
  215.                         if (!matchPattern(field.value, oMasked[x][2]("mask"))) {
  216.                             if (i == 0) {
  217.                                 focusField = field;
  218.                             }
  219.                             fields[i++] = oMasked[x][1];
  220.                             isValid = false;
  221.                         }
  222.                     }
  223.                 }
  224.                 
  225.                 if (fields.length > 0) {
  226.                    focusField.focus();
  227.                    alert(fields.join('\n'));
  228.                 }
  229.                 return isValid;
  230.             }

  231.             function matchPattern(value, mask) {
  232.                return mask.exec(value);
  233.             }]]>
  234.          

  235.       


  236.       
  237.             classname="org.apache.struts.validator.FieldChecks"
  238.                method="validateByte"
  239.          methodParams="java.lang.Object,
  240.                        org.apache.commons.validator.ValidatorAction,
  241.                        org.apache.commons.validator.Field,
  242.                        org.apache.struts.action.ActionErrors,
  243.                        javax.servlet.http.HttpServletRequest"
  244.               depends=""
  245.                   msg="errors.byte"
  246.        jsFunctionName="ByteValidations">

  247.          
  248.             function validateByte(form) {
  249.                 var bValid = true;
  250.                 var focusField = null;
  251.                 var i = 0;
  252.                 var fields = new Array();
  253.                 oByte = new ByteValidations();
  254.                 for (x in oByte) {
  255.                     var field = form[oByte[x][0]];
  256.                     
  257.                     if (field.type == 'text' ||
  258.                         field.type == 'textarea' ||
  259.                         field.type == 'select-one' ||
  260.                         field.type == 'radio') {

  261.                         var value = '';
  262.                         // get field's value
  263.                         if (field.type == "select-one") {
  264.                             var si = field.selectedIndex;
  265.                             if (si >= 0) {
  266.                                 value = field.options[si].value;
  267.                             }
  268.                         } else {
  269.                             value = field.value;
  270.                         }
  271.                         
  272.                         if (value.length > 0) {
  273.                             if (!isAllDigits(value)) {
  274.                                 bValid = false;
  275.                                 if (i == 0) {
  276.                                     focusField = field;
  277.                                 }
  278.                                 fields[i++] = oByte[x][1];

  279.                             } else {

  280.      var iValue = parseInt(value);
  281.      if (isNaN(iValue) || !(iValue >= -128 && iValue <= 127)) {
  282.      if (i == 0) {
  283.      focusField = field;
  284.      }
  285.      fields[i++] = oByte[x][1];
  286.      bValid = false;
  287.      }
  288.                             }
  289.                         }
  290.                         
  291.                     }
  292.                 }
  293.                 if (fields.length > 0) {
  294.                    focusField.focus();
  295.                    alert(fields.join('\n'));
  296.                 }
  297.                 return bValid;
  298.             }]]>
  299.          </javascript>

  300.       </validator>


  301.       <validator name="short"
  302.             classname="org.apache.struts.validator.FieldChecks"
  303.                method="validateShort"
  304.          methodParams="java.lang.Object,
  305.                        org.apache.commons.validator.ValidatorAction,
  306.                        org.apache.commons.validator.Field,
  307.                        org.apache.struts.action.ActionErrors,
  308.                        javax.servlet.http.HttpServletRequest"
  309.               depends=""
  310.                   msg="errors.short"
  311.        jsFunctionName="ShortValidations">

  312.          <javascript><![CDATA[
  313.             function validateShort(form) {
  314.                 var bValid = true;
  315.                 var focusField = null;
  316.                 var i = 0;
  317.                 var fields = new Array();
  318.                 oShort = new ShortValidations();
  319.                 for (x in oShort) {
  320.                     var field = form[oShort[x][0]];
  321.                     
  322.                     if (field.type == 'text' ||
  323.                         field.type == 'textarea' ||
  324.                         field.type == 'select-one' ||
  325.                         field.type == 'radio') {
  326.                         
  327.                         var value = '';
  328.                         // get field's value
  329.                         if (field.type == "select-one") {
  330.                             var si = field.selectedIndex;
  331.                             if (si >= 0) {
  332.                                 value = field.options[si].value;
  333.                             }
  334.                         } else {
  335.                             value = field.value;
  336.                         }
  337.                         
  338.                         if (value.length > 0) {
  339.                             if (!isAllDigits(value)) {
  340.                                 bValid = false;
  341.                                 if (i == 0) {
  342.                                     focusField = field;
  343.                                 }
  344.                                 fields[i++] = oShort[x][1];

  345.                             } else {
  346.                         
  347.      var iValue = parseInt(value);
  348.      if (isNaN(iValue) || !(iValue >= -32768 && iValue <= 32767)) {
  349.      if (i == 0) {
  350.      focusField = field;
  351.      }
  352.      fields[i++] = oShort[x][1];
  353.      bValid = false;
  354.      }
  355.      }
  356.                        }
  357.                     }
  358.                 }
  359.                 if (fields.length > 0) {
  360.                    focusField.focus();
  361.                    alert(fields.join('\n'));
  362.                 }
  363.                 return bValid;
  364.             }]]>
  365.          

  366.       


  367.       
  368.             classname="org.apache.struts.validator.FieldChecks"
  369.                method="validateInteger"
  370.          methodParams="java.lang.Object,
  371.                        org.apache.commons.validator.ValidatorAction,
  372.                        org.apache.commons.validator.Field,
  373.                        org.apache.struts.action.ActionErrors,
  374.                        javax.servlet.http.HttpServletRequest"
  375.               depends=""
  376.                   msg="errors.integer"
  377.        jsFunctionName="IntegerValidations">

  378.          
  379.             function validateInteger(form) {
  380.                 var bValid = true;
  381.                 var focusField = null;
  382.                 var i = 0;
  383.                 var fields = new Array();
  384.                 oInteger = new IntegerValidations();
  385.                 for (x in oInteger) {
  386.                     var field = form[oInteger[x][0]];

  387.                     if (field.type == 'text' ||
  388.                         field.type == 'textarea' ||
  389.                         field.type == 'select-one' ||
  390.                         field.type == 'radio') {
  391.                         
  392.                         var value = '';
  393.                         // get field's value
  394.                         if (field.type == "select-one") {
  395.                             var si = field.selectedIndex;
  396.                          if (si >= 0) {
  397.                              value = field.options[si].value;
  398.                          }
  399.                         } else {
  400.                             value = field.value;
  401.                         }
  402.                         
  403.                         if (value.length > 0) {
  404.                         
  405.                             if (!isAllDigits(value)) {
  406.                                 bValid = false;
  407.                                 if (i == 0) {
  408.      focusField = field;
  409.      }
  410.                          fields[i++] = oInteger[x][1];
  411.                         
  412.                             } else {
  413.      var iValue = parseInt(value);
  414.      if (isNaN(iValue) || !(iValue >= -2147483648 && iValue <= 2147483647)) {
  415.      if (i == 0) {
  416.      focusField = field;
  417.      }
  418.      fields[i++] = oInteger[x][1];
  419.      bValid = false;
  420.      }
  421.                            }
  422.                        }
  423.                     }
  424.                 }
  425.                 if (fields.length > 0) {
  426.                    focusField.focus();
  427.                    alert(fields.join('\n'));
  428.                 }
  429.                 return bValid;
  430.             }

  431.             function isAllDigits(argvalue) {
  432.                 argvalue = argvalue.toString();
  433.                 var validChars = "0123456789";
  434.                 var startFrom = 0;
  435.                 if (argvalue.substring(0, 2) == "0x") {
  436.                    validChars = "0123456789abcdefABCDEF";
  437.                    startFrom = 2;
  438.                 } else if (argvalue.charAt(0) == "0") {
  439.                    validChars = "01234567";
  440.                    startFrom = 1;
  441.                 } else if (argvalue.charAt(0) == "-") {
  442.                     startFrom = 1;
  443.                 }
  444.                 
  445.                 for (var n = startFrom; n < argvalue.length; n++) {
  446.                     if (validChars.indexOf(argvalue.substring(n, n+1)) == -1) return false;
  447.                 }
  448.                 return true;
  449.             }]]>
  450.          </javascript>

  451.       </validator>


  452.       <validator name="long"
  453.             classname="org.apache.struts.validator.FieldChecks"
  454.                method="validateLong"
  455.          methodParams="java.lang.Object,
  456.                        org.apache.commons.validator.ValidatorAction,
  457.                        org.apache.commons.validator.Field,
  458.                        org.apache.struts.action.ActionErrors,
  459.                        javax.servlet.http.HttpServletRequest"
  460.               depends=""
  461.                   msg="errors.long"/>


  462.       <validator name="float"
  463.             classname="org.apache.struts.validator.FieldChecks"
  464.                method="validateFloat"
  465.          methodParams="java.lang.Object,
  466.                        org.apache.commons.validator.ValidatorAction,
  467.                        org.apache.commons.validator.Field,
  468.                        org.apache.struts.action.ActionErrors,
  469.                        javax.servlet.http.HttpServletRequest"
  470.               depends=""
  471.                   msg="errors.float"
  472.        jsFunctionName="FloatValidations">

  473.          <javascript><![CDATA[
  474.             function validateFloat(form) {
  475.                 var bValid = true;
  476.                 var focusField = null;
  477.                 var i = 0;
  478.                 var fields = new Array();
  479.                 oFloat = new FloatValidations();
  480.                 for (x in oFloat) {
  481.                     var field = form[oFloat[x][0]];
  482.                     
  483.                     if (field.type == 'text' ||
  484.                         field.type == 'textarea' ||
  485.                         field.type == 'select-one' ||
  486.                         field.type == 'radio') {
  487.                         
  488.                         var value = '';
  489.                         // get field's value
  490.                         if (field.type == "select-one") {
  491.                             var si = field.selectedIndex;
  492.                             if (si >= 0) {
  493.                              value = field.options[si].value;
  494.                             }
  495.                         } else {
  496.                             value = field.value;
  497.                         }
  498.                         
  499.                         if (value.length > 0) {
  500.                             // remove '.' before checking digits
  501.                             var tempArray = value.split('.');
  502.                             var joinedString= tempArray.join('');

  503.                             if (!isAllDigits(joinedString)) {
  504.                                 bValid = false;
  505.                                 if (i == 0) {
  506.                                     focusField = field;
  507.                                 }
  508.                                 fields[i++] = oFloat[x][1];

  509.                             } else {
  510.      var iValue = parseFloat(value);
  511.      if (isNaN(iValue)) {
  512.      if (i == 0) {
  513.      focusField = field;
  514.      }
  515.      fields[i++] = oFloat[x][1];
  516.      bValid = false;
  517.      }
  518.                             }
  519.                         }
  520.                     }
  521.                 }
  522.                 if (fields.length > 0) {
  523.                    focusField.focus();
  524.                    alert(fields.join('\n'));
  525.                 }
  526.                 return bValid;
  527.             }]]>
  528.          

  529.       


  530.       
  531.             classname="org.apache.struts.validator.FieldChecks"
  532.                method="validateDouble"
  533.          methodParams="java.lang.Object,
  534.                        org.apache.commons.validator.ValidatorAction,
  535.                        org.apache.commons.validator.Field,
  536.                        org.apache.struts.action.ActionErrors,
  537.                        javax.servlet.http.HttpServletRequest"
  538.               depends=""
  539.                   msg="errors.double"/>


  540.       
  541.             classname="org.apache.struts.validator.FieldChecks"
  542.                method="validateDate"
  543.          methodParams="java.lang.Object,
  544.                        org.apache.commons.validator.ValidatorAction,
  545.                        org.apache.commons.validator.Field,
  546.                        org.apache.struts.action.ActionErrors,
  547.                        javax.servlet.http.HttpServletRequest"
  548.               depends=""
  549.                   msg="errors.date"
  550.        jsFunctionName="DateValidations">

  551.          
  552.             function validateDate(form) {
  553.                var bValid = true;
  554.                var focusField = null;
  555.                var i = 0;
  556.                var fields = new Array();
  557.                oDate = new DateValidations();
  558.                for (x in oDate) {
  559.                    var value = form[oDate[x][0]].value;
  560.                    var datePattern = oDate[x][2]("datePatternStrict");
  561.                    if ((form[oDate[x][0]].type == 'text' ||
  562.                         form[oDate[x][0]].type == 'textarea') &&
  563.                        (value.length > 0) &&
  564.                        (datePattern.length > 0)) {
  565.                      var MONTH = "MM";
  566.                      var DAY = "dd";
  567.                      var YEAR = "yyyy";
  568.                      var orderMonth = datePattern.indexOf(MONTH);
  569.                      var orderDay = datePattern.indexOf(DAY);
  570.                      var orderYear = datePattern.indexOf(YEAR);
  571.                      if ((orderDay < orderYear && orderDay > orderMonth)) {
  572.                          var iDelim1 = orderMonth + MONTH.length;
  573.                          var iDelim2 = orderDay + DAY.length;
  574.                          var delim1 = datePattern.substring(iDelim1, iDelim1 + 1);
  575.                          var delim2 = datePattern.substring(iDelim2, iDelim2 + 1);
  576.                          if (iDelim1 == orderDay && iDelim2 == orderYear) {
  577.                             dateRegexp = new RegExp("^(\\d{2})(\\d{2})(\\d{4})$");
  578.                          } else if (iDelim1 == orderDay) {
  579.                             dateRegexp = new RegExp("^(\\d{2})(\\d{2})[" + delim2 + "](\\d{4})$");
  580.                          } else if (iDelim2 == orderYear) {
  581.                             dateRegexp = new RegExp("^(\\d{2})[" + delim1 + "](\\d{2})(\\d{4})$");
  582.                          } else {
  583.                             dateRegexp = new RegExp("^(\\d{2})[" + delim1 + "](\\d{2})[" + delim2 + "](\\d{4})$");
  584.                          }
  585.                          var matched = dateRegexp.exec(value);
  586.                          if(matched != null) {
  587.                             if (!isValidDate(matched[2], matched[1], matched[3])) {
  588.                                if (i == 0) {
  589.                                    focusField = form[oDate[x][0]];
  590.                                }
  591.                                fields[i++] = oDate[x][1];
  592.                                bValid = false;
  593.                             }
  594.                          } else {
  595.                             if (i == 0) {
  596.                                 focusField = form[oDate[x][0]];
  597.                             }
  598.                             fields[i++] = oDate[x][1];
  599.                             bValid = false;
  600.                          }
  601.                      } else if ((orderMonth < orderYear && orderMonth > orderDay)) {
  602.                          var iDelim1 = orderDay + DAY.length;
  603.                          var iDelim2 = orderMonth + MONTH.length;
  604.                          var delim1 = datePattern.substring(iDelim1, iDelim1 + 1);
  605.                          var delim2 = datePattern.substring(iDelim2, iDelim2 + 1);
  606.                          if (iDelim1 == orderMonth && iDelim2 == orderYear) {
  607.                              dateRegexp = new RegExp("^(\\d{2})(\\d{2})(\\d{4})$");
  608.                          } else if (iDelim1 == orderMonth) {
  609.                              dateRegexp = new RegExp("^(\\d{2})(\\d{2})[" + delim2 + "](\\d{4})$");
  610.                          } else if (iDelim2 == orderYear) {
  611.                              dateRegexp = new RegExp("^(\\d{2})[" + delim1 + "](\\d{2})(\\d{4})$");
  612.                          } else {
  613.                              dateRegexp = new RegExp("^(\\d{2})[" + delim1 + "](\\d{2})[" + delim2 + "](\\d{4})$");
  614.                          }
  615.                          var matched = dateRegexp.exec(value);
  616.                          if(matched != null) {
  617.                              if (!isValidDate(matched[1], matched[2], matched[3])) {
  618.                                  if (i == 0) {
  619.                                      focusField = form[oDate[x][0]];
  620.                                  }
  621.                                  fields[i++] = oDate[x][1];
  622.                                  bValid = false;
  623.                               }
  624.                          } else {
  625.                              if (i == 0) {
  626.                                  focusField = form[oDate[x][0]];
  627.                              }
  628.                              fields[i++] = oDate[x][1];
  629.                              bValid = false;
  630.                          }
  631.                      } else if ((orderMonth > orderYear && orderMonth < orderDay)) {
  632.                          var iDelim1 = orderYear + YEAR.length;
  633.                          var iDelim2 = orderMonth + MONTH.length;
  634.                          var delim1 = datePattern.substring(iDelim1, iDelim1 + 1);
  635.                          var delim2 = datePattern.substring(iDelim2, iDelim2 + 1);
  636.                          if (iDelim1 == orderMonth && iDelim2 == orderDay) {
  637.                              dateRegexp = new RegExp("^(\\d{4})(\\d{2})(\\d{2})$");
  638.                          } else if (iDelim1 == orderMonth) {
  639.                              dateRegexp = new RegExp("^(\\d{4})(\\d{2})[" + delim2 + "](\\d{2})$");
  640.                          } else if (iDelim2 == orderDay) {
  641.                              dateRegexp = new RegExp("^(\\d{4})[" + delim1 + "](\\d{2})(\\d{2})$");
  642.                          } else {
  643.                              dateRegexp = new RegExp("^(\\d{4})[" + delim1 + "](\\d{2})[" + delim2 + "](\\d{2})$");
  644.                          }
  645.                          var matched = dateRegexp.exec(value);
  646.                          if(matched != null) {
  647.                              if (!isValidDate(matched[3], matched[2], matched[1])) {
  648.                                  if (i == 0) {
  649.                                      focusField = form[oDate[x][0]];
  650.                                   }
  651.                                   fields[i++] = oDate[x][1];
  652.                                   bValid = false;
  653.                               }
  654.                           } else {
  655.                               if (i == 0) {
  656.                                   focusField = form[oDate[x][0]];
  657.                               }
  658.                               fields[i++] = oDate[x][1];
  659.                               bValid = false;
  660.                           }
  661.                      } else {
  662.                          if (i == 0) {
  663.                              focusField = form[oDate[x][0]];
  664.                          }
  665.                          fields[i++] = oDate[x][1];
  666.                          bValid = false;
  667.                      }
  668.                   }
  669.                }
  670.                if (fields.length > 0) {
  671.                   focusField.focus();
  672.                   alert(fields.join('\n'));
  673.                }
  674.                return bValid;
  675.             }

  676.      function isValidDate(day, month, year) {
  677.      if (month < 1 || month > 12) {
  678.                     return false;
  679.                 }
  680.                 if (day < 1 || day > 31) {
  681.                     return false;
  682.                 }
  683.                 if ((month == 4 || month == 6 || month == 9 || month == 11) &&
  684.                     (day == 31)) {
  685.                     return false;
  686.                 }
  687.                 if (month == 2) {
  688.                     var leap = (year % 4 == 0 &&
  689.                                (year % 100 != 0 || year % 400 == 0));
  690.                     if (day>29 || (day == 29 && !leap)) {
  691.                         return false;
  692.                     }
  693.                 }
  694.                 return true;
  695.             }]]>
  696.          

  697.       


  698.       
  699.             classname="org.apache.struts.validator.FieldChecks"
  700.                method="validateIntRange"
  701.          methodParams="java.lang.Object,
  702.                        org.apache.commons.validator.ValidatorAction,
  703.                        org.apache.commons.validator.Field,
  704.                        org.apache.struts.action.ActionErrors,
  705.                        javax.servlet.http.HttpServletRequest"
  706.               depends="integer"
  707.                   msg="errors.range">

  708.          
  709.             function validateRange(form) {
  710.                 return validateIntRange(form);
  711.             }]]>
  712.          

  713.       

  714.       
  715.             classname="org.apache.struts.validator.FieldChecks"
  716.                method="validateIntRange"
  717.          methodParams="java.lang.Object,
  718.                        org.apache.commons.validator.ValidatorAction,
  719.                        org.apache.commons.validator.Field,
  720.                        org.apache.struts.action.ActionErrors,
  721.                        javax.servlet.http.HttpServletRequest"
  722.               depends="integer"
  723.                   msg="errors.range">

  724.          
  725.             function validateIntRange(form) {
  726.                 var isValid = true;
  727.                 var focusField = null;
  728.                 var i = 0;
  729.                 var fields = new Array();
  730.                 oRange = new intRange();
  731.                 for (x in oRange) {
  732.                     var field = form[oRange[x][0]];
  733.                     
  734.                     if ((field.type == 'text' ||
  735.                          field.type == 'textarea') &&
  736.                         (field.value.length > 0)) {
  737.                         
  738.                         var iMin = parseInt(oRange[x][2]("min"));
  739.                         var iMax = parseInt(oRange[x][2]("max"));
  740.                         var iValue = parseInt(field.value);
  741.                         if (!(iValue >= iMin && iValue <= iMax)) {
  742.                             if (i == 0) {
  743.                                 focusField = field;
  744.                             }
  745.                             fields[i++] = oRange[x][1];
  746.                             isValid = false;
  747.                         }
  748.                     }
  749.                 }
  750.                 if (fields.length > 0) {
  751.                     focusField.focus();
  752.                     alert(fields.join('\n'));
  753.                 }
  754.                 return isValid;
  755.             }]]>
  756.          

  757.       

  758.       
  759.             classname="org.apache.struts.validator.FieldChecks"
  760.                method="validateFloatRange"
  761.          methodParams="java.lang.Object,
  762.                        org.apache.commons.validator.ValidatorAction,
  763.                        org.apache.commons.validator.Field,
  764.                        org.apache.struts.action.ActionErrors,
  765.                        javax.servlet.http.HttpServletRequest"
  766.               depends="float"
  767.                   msg="errors.range">

  768.          
  769.             function validateFloatRange(form) {
  770.                 var isValid = true;
  771.                 var focusField = null;
  772.                 var i = 0;
  773.                 var fields = new Array();
  774.                 oRange = new floatRange();
  775.                 for (x in oRange) {
  776.                     var field = form[oRange[x][0]];
  777.                     
  778.                     if ((field.type == 'text' ||
  779.                          field.type == 'textarea') &&
  780.                         (field.value.length > 0)) {
  781.                         
  782.                         var fMin = parseFloat(oRange[x][2]("min"));
  783.                         var fMax = parseFloat(oRange[x][2]("max"));
  784.                         var fValue = parseFloat(field.value);
  785.                         if (!(fValue >= fMin && fValue <= fMax)) {
  786.                             if (i == 0) {
  787.                                 focusField = field;
  788.                             }
  789.                             fields[i++] = oRange[x][1];
  790.                             isValid = false;
  791.                         }
  792.                     }
  793.                 }
  794.                 if (fields.length > 0) {
  795.                     focusField.focus();
  796.                     alert(fields.join('\n'));
  797.                 }
  798.                 return isValid;
  799.             }]]>
  800.          

  801.       

  802.       
  803.             classname="org.apache.struts.validator.FieldChecks"
  804.                method="validateCreditCard"
  805.          methodParams="java.lang.Object,
  806.                        org.apache.commons.validator.ValidatorAction,
  807.                        org.apache.commons.validator.Field,
  808.                        org.apache.struts.action.ActionErrors,
  809.                        javax.servlet.http.HttpServletRequest"
  810.               depends=""
  811.                   msg="errors.creditcard">

  812.          
  813.             function validateCreditCard(form) {
  814.                 var bValid = true;
  815.                 var focusField = null;
  816.                 var i = 0;
  817.                 var fields = new Array();
  818.                 oCreditCard = new creditCard();
  819.                 for (x in oCreditCard) {
  820.                     if ((form[oCreditCard[x][0]].type == 'text' ||
  821.                          form[oCreditCard[x][0]].type == 'textarea') &&
  822.                         (form[oCreditCard[x][0]].value.length > 0)) {
  823.                         if (!luhnCheck(form[oCreditCard[x][0]].value)) {
  824.                             if (i == 0) {
  825.                                 focusField = form[oCreditCard[x][0]];
  826.                             }
  827.                             fields[i++] = oCreditCard[x][1];
  828.                             bValid = false;
  829.                         }
  830.                     }
  831.                 }
  832.                 if (fields.length > 0) {
  833.                     focusField.focus();
  834.                     alert(fields.join('\n'));
  835.                 }
  836.                 return bValid;
  837.             }

  838.             /**
  839.              * Reference: ~sburke/pub/luhn_lib.pl
  840.              */
  841.             function luhnCheck(cardNumber) {
  842.                 if (isLuhnNum(cardNumber)) {
  843.                     var no_digit = cardNumber.length;
  844.                     var oddoeven = no_digit & 1;
  845.                     var sum = 0;
  846.                     for (var count = 0; count < no_digit; count++) {
  847.                         var digit = parseInt(cardNumber.charAt(count));
  848.                         if (!((count & 1) ^ oddoeven)) {
  849.                             digit *= 2;
  850.                             if (digit > 9) digit -= 9;
  851.                         };
  852.                         sum += digit;
  853.                     };
  854.                     if (sum == 0) return false;
  855.                     if (sum % 10 == 0) return true;
  856.                 };
  857.                 return false;
  858.             }

  859.             function isLuhnNum(argvalue) {
  860.                 argvalue = argvalue.toString();
  861.                 if (argvalue.length == 0) {
  862.                     return false;
  863.                 }
  864.                 for (var n = 0; n < argvalue.length; n++) {
  865.                     if ((argvalue.substring(n, n+1) < "0") ||
  866.                         (argvalue.substring(n,n+1) > "9")) {
  867.                         return false;
  868.                     }
  869.                 }
  870.                 return true;
  871.             }]]>
  872.          

  873.       


  874.       
  875.             classname="org.apache.struts.validator.FieldChecks"
  876.                method="validateEmail"
  877.          methodParams="java.lang.Object,
  878.                        org.apache.commons.validator.ValidatorAction,
  879.                        org.apache.commons.validator.Field,
  880.                        org.apache.struts.action.ActionErrors,
  881.                        javax.servlet.http.HttpServletRequest"
  882.               depends=""
  883.                   msg="errors.email">

  884.          
  885.             function validateEmail(form) {
  886.                 var bValid = true;
  887.                 var focusField = null;
  888.                 var i = 0;
  889.                 var fields = new Array();
  890.                 oEmail = new email();
  891.                 for (x in oEmail) {
  892.                     if ((form[oEmail[x][0]].type == 'text' ||
  893.                          form[oEmail[x][0]].type == 'textarea') &&
  894.                         (form[oEmail[x][0]].value.length > 0)) {
  895.                         if (!checkEmail(form[oEmail[x][0]].value)) {
  896.                             if (i == 0) {
  897.                                 focusField = form[oEmail[x][0]];
  898.                             }
  899.                             fields[i++] = oEmail[x][1];
  900.                             bValid = false;
  901.                         }
  902.                     }
  903.                 }
  904.                 if (fields.length > 0) {
  905.                     focusField.focus();
  906.                     alert(fields.join('\n'));
  907.                 }
  908.                 return bValid;
  909.             }

  910.             /**
  911.              * Reference: Sandeep V. Tamhankar (stamhankar@hotmail.com),
  912.              *
  913.              */
  914.             function checkEmail(emailStr) {
  915.                if (emailStr.length == 0) {
  916.                    return true;
  917.                }
  918.                var emailPat=/^(.+)@(.+)$/;
  919.                var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
  920.                var validChars="\[^\\s" + specialChars + "\]";
  921.                var quotedUser="(\"[^\"]*\")";
  922.                var ipDomainPat=/^(\d{1,3})[.](\d{1,3})[.](\d{1,3})[.](\d{1,3})$/;
  923.                var atom=validChars + '+
struts-config.xml中加入

点击(此处)折叠或打开

  1. <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
  2.     <set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml" />
  3.   </plug-in>

最后附加代码: validatesample.rar   
阅读(2135) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~