参考:
https://docs.jboss.org/hibernate/validator/4.3/reference/zh-CN/html/validator-customconstraints.html#validator-customconstraints-errormessage
https://www.ibm.com/developerworks/cn/java/j-lo-beanvalid/index.html
https://blog.csdn.net/qq920447939/article/details/80198438
入参的校验很多啊,不能为空,必须为手机号,必须为中文等等等等。下面是归类。
一 已有的参数校验规则
在你的dto上直接用注解定义校验规则,都是些常见的实用的规则
@Getter
@Setter
public class FormContent implements Serializable {
@NotNull(message = "serialNo必须有值")
String serialNo;
@NotBlank(message = "id不能为空")
String id;
@Email(message = "email不是一个合法的电子邮件地址|为空时不会判定")
String email;
@NotBlank(message = "手机号不能为空")
@Pattern(regexp = "^(1)\\d{10}$", message = "请输入正确的手机号")
String mobile;
@NotBlank(message = "身份证号码不能为空")
@Pattern(regexp = "^(\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)", message = "请输入正确的身份证号码")
String idCardNo;
@Pattern(regexp = "^[\\u4E00-\\u9FA5\\uf900-\\ufa2d·s]+$", message = "姓名只支持:中文和符号·")
@Length(min = 1, max = 20, message = "姓名长度不符合规范")
@NotBlank(message = "姓名不能为空")
String name;
@AssertTrue(message = "agree只能为true")
boolean agree;
//级联验证
@Valid
@NotNull(message = "地址不能为空")
Address address;
@DecimalMin(value = "0.00", message = "金额必须大于0")
@DecimalMax(value = "10000.00", message = "金额必须小于10000")
String amount;
@Size(min = 1, max = 5, message = "爱好大于1个,小于5个")
final List<String> hobbies = new ArrayList<>();
@Future(message = "expireTime is not less than now")
Date expireTime;
}
@Builder
@Getter
@Setter
public class Address {
@NotBlank(message = "省为空")
String province;
@NotBlank(message = "市为空")
String city;
@NotBlank(message = "区为空")
String region;
@Length(min = 1, max = 50, message = "详细地址长度不符合规范")
@NotBlank(message = "详细地址为空")
String address;
}
具体校验工具(可以写在切面,统一校验就完事了)
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Set;
public class ValidateCheckUtils {
private static Validator validator;
public static <T> void check(T obj) {
if (validator == null) {
validator = Validation.buildDefaultValidatorFactory().getValidator();
}
Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
if (set != null && set.size() > 0) {
String property = null;
for (ConstraintViolation<T> cv : set) {
//这里循环获取错误信息,可以自定义格式
property = cv.getMessage();
throw new IllegalArgumentException(property);
}
}
}
}
二 你也可以自定义校验规则
比如要校验字符串类型的日期,满足yyyy-MM-dd之类的格式。
首先,定义一个注解
@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = CheckDateValidator.class)
@Documented
public @interface CheckDate {
String message() default "日期不合规范";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String format() default "yyyy-MM-dd";
}
然后定义具体的校验方法
public class CheckDateValidator implements ConstraintValidator<CheckDate, String> {
private String format;
public void initialize(CheckDate constraintAnnotation) {
this.format = constraintAnnotation.format();
}
public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
if (object == null)
return true;
String pattern = format;
boolean isValid = true;
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
// 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
format.setLenient(false);
format.parse(object);
} catch (Exception ex) {
isValid = false;
}
return isValid;
}
}
具体调用
public static void main(String[] args) {
FormContent formContent = new FormContent();
formContent.setSerialNo("");
formContent.setId("123");
formContent.setEmail("");
formContent.setMobile("15012345678");
formContent.setIdCardNo("123456789012345");
formContent.setAgree(true);
formContent.setName("张三·买买提");
Address address = Address.builder()
.province("重庆市")
.region("市辖区")
.city("渝中区")
.address("解放碑").build();
formContent.setAddress(address);
formContent.setAmount("1000.00");
formContent.getHobbies().add("xixixi");
formContent.getHobbies().add("hahaha");
Calendar calendar = Calendar.getInstance();
calendar.set(2020, 10, 1);
Date date = calendar.getTime();
formContent.setExpireTime(date);
formContent.setLowerCase("asdasd");
formContent.setCreateTime("2019-09-11");
ValidateCheckUtils.check(formContent);
}
完事~