springboot数据格式验证(二)——自定义日期格式验证
上篇文章说javax.validation
包与hibernate-validator
包中注解能解决80%的问题,那剩下20%的问题咋解决?
答案是自定义注解来解决
我们在工作中经常需要对日期格式进行定义,如果客户端传来的日期字符串不符合要求,那么根本无法保存,但是已有的注解并没有日期格式的验证,那我们就自己实现一个
一、自定义日期格式验证的注解@DateFormat
注解里需要写明用来具体处理验证逻辑的类,这里对应的就是DateFormatValidator.class
@Target({ElementType.PARAMETER, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = DateFormatValidator.class) public @interface DateFormat { String message() default "日期格式错误"; String format() default "yyyy-MM-dd"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
二、验证逻辑处理类
public class DateFormatValidator implements ConstraintValidator<DateFormat, String> { private DateFormat dateFormat; @Override public void initialize(DateFormat dateFormat) { this.dateFormat = dateFormat; } @Override public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) { String format = dateFormat.format(); if (format.equals("yyyy-MM")) { DateTimeFormatter dtf1 = new DateTimeFormatterBuilder() .appendPattern(format) .parseDefaulting(ChronoField.DAY_OF_MONTH, 1) .toFormatter(); try { LocalDate.parse(s, dtf1); } catch (Exception e) { return false; } } else { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format); try { simpleDateFormat.parse(s); } catch (Exception e) { return false; } } return true; } }
这个月数据yyyy-MM需要特殊处理的原因在于,如果提供的是yyyy-MM-dd的格式的字符串,使用SimpleDateFormat("yyyy-MM")去解析也不会失败
三、自定义注解的应用
public class Tables implements Serializable { private static final long serialVersionUID = -3596411984380984035L; @ApiModelProperty("表名,必须为英文小写") @NotNull(message = "tbName不能为空") private String tbName; @ApiModelProperty("表描述") @NotNull(message = "chineseName不能为空") private String chineseName; @ApiModelProperty("表唯一键") private String uniqueKey; @ApiModelProperty("创建日期") @DateFormat(format = "yyyy-MM-dd",message = "日期格式错误,正确格式为yyyy-MM-dd") private String createDate; }
四、controller层的使用
@PostMapping("addTable") @ApiOperation("增加一个表") public BaseResponse<String> addTable(@Validated @RequestBody Tables tables, BindingResult br) { if (br.hasErrors()) { String defaultMessage = br.getFieldError().getDefaultMessage(); return BaseResultUtils.error(defaultMessage); } else { modelService.createTB(tables); return BaseResultUtils.success(null); } }
五、最终效果
参考:
https://blog.csdn.net/qq_40775879/article/details/86302695
https://www.jianshu.com/p/67d3637493c7
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
2020-07-13 在Scala中使用fastJson