2016-06-17 46 views
0

我想使用Hibernate验证器验证我的方法的参数。如何将JSR 303验证添加到方法的参数

我试图查找的例子,并通过下面的例子 JSR 303. Validate method parameter and throw exception

去但答案并不完全解决我的问题,也是链接在回答过期。

下面是我尝试过的示例代码。

//removing imports to reduce the length of code. 

/** 
* Created by Nick on 15/06/2016. 
*/ 

@Component 
public class ValidationService { 

    @Value("${namesAllowed}") 
    private String validNames; 

    @Autowired 
    private Validator validator; 

    public boolean validateName(
      @NotEmpty 
      @Pattern(regexp = ".*'.*'.*") 
      @Email 
      @Length(max = 10) 
        String name 
    ) { 

     Set<ConstraintViolation<String>> violations = validator.validate(name); 

     for (ConstraintViolation<String> violation : violations) { 
      String propertyPath = violation.getPropertyPath().toString(); 
      String message = violation.getMessage(); 
      System.out.println("invalid value for: '" + propertyPath + "': " + message); 
     } 
     List<String> namesAllowed= Arrays.asList(validNames.split(",")); 
     if (namesAllowed.contains(name.substring(name.indexOf(".") + 1))) { 
      return true; 
     } 
     return false; 
    } 
} 

}

回答