validator 自定义验证规则

1. 定义自己的验证方法类:
java 代码
java 代码
  1.  public static boolean validateTwoFields(Object bean, ValidatorAction va,   
  2.                                             Field field, ActionMessages errors,   
  3.                                             HttpServletRequest request) {   
  4.         String value =   
  5.            ValidatorUtils.getValueAsString(bean, field.getProperty());//得到用户输入的该filed的值   
  6.         String sProperty2 = field.getVarValue("secondProperty"); //得到定义在field的变量(validation.xml中),此处指定的是另一个field name   
  7.         String value2 = ValidatorUtils.getValueAsString(bean, sProperty2);   
  8.   
  9.         if (!GenericValidator.isBlankOrNull(value)) {   
  10.             try {   
  11.                 if (!value.equals(value2)) {   
  12.                     errors.add(field.getKey(),   
  13.                                Resources.getActionMessage(request, va, field));   
  14.   
  15.                     return false;   
  16.                 }   
  17.             } catch (Exception e) {   
  18.                 errors.add(field.getKey(),   
  19.                            Resources.getActionMessage(request, va, field));   
  20.   
  21.                 return false;   
  22.             }   
  23.         }   
  24.   
  25.         return true;   
  26.     }   
  27. }   

 2  .到validator-rule-custom.xml加入你定制的rule.

xml 代码
  1. <field property="password"  
  2.                    depends="required,twofields">  
  3.                 <msg  
  4.                   name="twofields"  
  5.                   key="errors.twofields"/>  
  6.   
  7.                 <arg0 key="userForm.password"/>  
  8.                 <arg1  
  9.                   key="userForm.confirmPassword"  
  10.                 />  
  11.                 <var>  
  12.                   <var-name>secondPropertyvar-name>  
  13.                   <var-value>confirmPasswordvar-value>  
  14.                 var>  
  15.             field>  
  16.             <field property="confirmPassword"  
  17.                    depends="required">  
  18.   
  19.                 <arg0 key="userForm.confirmPassword"/>  
  20.             field>  

你可能感兴趣的:(struts,Bean,XML)