提交 | 用户 | 时间
|
e7c126
|
1 |
package com.iailab.framework.common.util.validation; |
H |
2 |
|
|
3 |
import cn.hutool.core.collection.CollUtil; |
|
4 |
import cn.hutool.core.lang.Assert; |
|
5 |
import org.springframework.util.StringUtils; |
|
6 |
|
|
7 |
import javax.validation.ConstraintViolation; |
|
8 |
import javax.validation.ConstraintViolationException; |
|
9 |
import javax.validation.Validation; |
|
10 |
import javax.validation.Validator; |
|
11 |
import java.util.Set; |
|
12 |
import java.util.regex.Pattern; |
|
13 |
|
|
14 |
/** |
|
15 |
* 校验工具类 |
|
16 |
* |
|
17 |
* @author iailab |
|
18 |
*/ |
|
19 |
public class ValidationUtils { |
|
20 |
|
|
21 |
private static final Pattern PATTERN_MOBILE = Pattern.compile("^(?:(?:\\+|00)86)?1(?:(?:3[\\d])|(?:4[0,1,4-9])|(?:5[0-3,5-9])|(?:6[2,5-7])|(?:7[0-8])|(?:8[\\d])|(?:9[0-3,5-9]))\\d{8}$"); |
|
22 |
|
|
23 |
private static final Pattern PATTERN_URL = Pattern.compile("^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"); |
|
24 |
|
|
25 |
private static final Pattern PATTERN_XML_NCNAME = Pattern.compile("[a-zA-Z_][\\-_.0-9_a-zA-Z$]*"); |
|
26 |
|
|
27 |
public static boolean isMobile(String mobile) { |
|
28 |
return StringUtils.hasText(mobile) |
|
29 |
&& PATTERN_MOBILE.matcher(mobile).matches(); |
|
30 |
} |
|
31 |
|
|
32 |
public static boolean isURL(String url) { |
|
33 |
return StringUtils.hasText(url) |
|
34 |
&& PATTERN_URL.matcher(url).matches(); |
|
35 |
} |
|
36 |
|
|
37 |
public static boolean isXmlNCName(String str) { |
|
38 |
return StringUtils.hasText(str) |
|
39 |
&& PATTERN_XML_NCNAME.matcher(str).matches(); |
|
40 |
} |
|
41 |
|
|
42 |
public static void validate(Object object, Class<?>... groups) { |
|
43 |
Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); |
|
44 |
Assert.notNull(validator); |
|
45 |
validate(validator, object, groups); |
|
46 |
} |
|
47 |
|
|
48 |
public static void validate(Validator validator, Object object, Class<?>... groups) { |
|
49 |
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups); |
|
50 |
if (CollUtil.isNotEmpty(constraintViolations)) { |
|
51 |
throw new ConstraintViolationException(constraintViolations); |
|
52 |
} |
|
53 |
} |
|
54 |
|
|
55 |
} |