Created
December 9, 2019 08:51
-
-
Save keepingcoding/a712ec71178c49518cc29b6e4ddc7169 to your computer and use it in GitHub Desktop.
JSR 303 - Bean校验工具类
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.validation.*; | |
import java.util.*; | |
/** | |
* 校验工具类 | |
*/ | |
public class ValidationUtils { | |
/** | |
* @param t 要校验的数据 | |
* @param skipFields 不需要校验的字段 | |
* @return | |
*/ | |
public static <T> Map<String, List<String>> validator(T t, HashSet<String> skipFields) { | |
ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); | |
Validator validator = factory.getValidator(); | |
Set<ConstraintViolation<T>> constraintViolations = validator.validate(t); | |
if (constraintViolations != null && constraintViolations.size() > 0) { | |
Map<String, List<String>> mapErr = new HashMap<>(); | |
for (ConstraintViolation<T> constraintViolation : constraintViolations) { | |
for (Path.Node node : constraintViolation.getPropertyPath()) { | |
String fieldName = node.getName(); | |
//跳过校验的属性,校验错误不加入错误列表 | |
if (skipFields == null || !skipFields.contains(fieldName)) { | |
List<String> lst = mapErr.get(fieldName); | |
if (lst == null) { | |
lst = new ArrayList<>(); | |
} | |
lst.add(constraintViolation.getMessage()); | |
mapErr.put(node.getName(), lst); | |
} | |
} | |
} | |
return mapErr; | |
} | |
return null; | |
} | |
public static <T> Map<String, List<String>> validator(T t) { | |
return validator(t, null); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment