首页
学习
活动
专区
圈层
工具
发布
25 篇文章
1
SpringBoot2.x系列教程(五十九)SpringBoot实现国际化i18n功能
2
SpringBoot2.x系列教程(五十五)Mybatis反向生成Java代码
3
SpringBoot2.x系列教程(四十四)WebSocket基础知识简介
4
SpringBoot2.x系列教程(四十三)SpringBoot整合Swagger2
5
SpringBoot2.x系列教程(五十)Spring Boot Idea中热部署(自动刷新)
6
SpringBoot2.x系列教程(四十二)SpringBoot中构建RESTful服务
7
SpringBoot2.x系列教程(三十八)SpringBoot配置Https访问
8
SpringBoot2.x系列教程(三十六)SpringBoot之Tomcat配置
9
SpringBoot2.x系列教程(三十四)Thymeleaf自动配置源码解析
10
SpringBoot2.x系列教程(三十三)Thymeleaf手动渲染实例讲解
11
SpringBoot2.x系列教程(三十二)Thymeleaf资源导入及公共布局
12
SpringBoot2.x系列教程(三十一)Thymeleaf的基本使用
13
SpringBoot2.x系列教程(三十)SpringBoot集成Thymeleaf
14
SpringBoot2.x系列教程(二十九)freemarker自动配置源码解析
15
SpringBoot2.x系列教程(二十八)freemarker基本语法使用
16
SpringBoot2.x系列教程(二十六)Springboot集成freemarker
17
SpringBoot2.x系列教程(二十五)Jsp中使用jstl和引入静态资源
18
SpringBoot2.x系列教程(二十三)SpringBoot集成Jsp
19
SpringBoot2.x系列教程(二十二)简单参数校验及统一异常处理
20
SpringBoot2.x系列教程(二十)自定义参数校验注解
21
SpringBoot2.x系列教程(十三)Jackson命名策略及自定义序列化
22
SpringBoot2.x系列教程(十)Json之基础使用详解
23
SpringBoot2.x系列教程(十九)Validation数据校验基础使用
24
SpringBoot2.x系列教程(九)基于Postman的RESTful接口调用
25
SpringBoot2.x系列教程(八)SpringBoot常用注解汇总

SpringBoot2.x系列教程(二十)自定义参数校验注解

在SpringBoot的使用过程中,默认使用hibernate-validator作为参数校验的框架,但某些业务场景或校验比较复杂,通过默认提供的注解已经无法满足。此时,除了使用正则表达式来进行校验也可以使用自定义的注解。

比如,对于手机号的简单校验如下:

代码语言:javascript
复制
@Pattern(regexp = "^1(3|4|5|7|8)\\d{9}$", message = "手机号码格式错误")
@NotBlank(message = "手机号码不能为空")
private String phone;

虽然能够完成工作,但是如果多出都出现类似的功能或更复杂的功能,每次都写如此多内容,显得有些臃肿。那么,我们这篇文章就来展示如何通过自定义注解来完成相同的功能。

自定义注解

我们知道hibernate validation实现JSR的标准,同时提供了一些API和扩展性的规范。要实现自定义注解,可以通过实现ConstraintValidator接口来完成。

下面看具体示例,首先定义手机号校验注解@Phone。

代码语言:javascript
复制
/**
 * 手机号校验
 * @author zzs
 */
@Target({ ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PhoneValidator.class)
public @interface Phone {

	/**
	 * 错误提示
	 */
	String message() default "手机号格式错误";
	/**
	 * 分组校验
	 */
	Class<?>[] groups() default {};

	Class<? extends Payload>[] payload() default {};
}

这里的@Phone注解组合了@Constraint注解,并通过其指定了真正进行校验类。

其中message为定制化的提示信息;groups主要进行将validato

下一篇
举报
领券