# 数据校验框架
**Repository Path**: weiyiee/data_checking_framework
## Basic Information
- **Project Name**: 数据校验框架
- **Description**: 一个简单的数据校验框架,不依赖任何第三方jar
- **Primary Language**: Java
- **License**: Apache-2.0
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 5
- **Forks**: 0
- **Created**: 2018-04-06
- **Last Updated**: 2020-12-19
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# 数据校验框架
一个简单的数据校验框架,不依赖任何第三方jar
**
使用示例:
**
要校验的实体类
```
public class ObjectRequireEntiry {
@NotBlank()
@Name("生日")
@DateFormat("yyyy-MM-dd")
private String birthday;
@Name("手机号码")
@Phone
private String phone;
@Name("身高")
@Max(230)
@Min(1)
private Integer stature;
@Name("体重")
@Max(200)
@Min(1)
private Integer weight;
@Name("对象要求")
@Length(min=0,max=200)
private String require_back;
get...
set...
}
```
校验
```
ValidateResult result = AnnotationValidator.validate(objectRequireEntiry);
if(!result.isValid()){
map.put("msg",result.getMessage());
map.put("field",result.getFieldName());
return map;
}
```
**可用注解
**
DateFormat:时间格式化
Length:长度限制
Max:最大数字
Min:最小数字
Name:属性名称(主要是用于向前端提示错误时,显示的属性名)
NotBlank:不允许为空
Phone:手机号码校验
**自定义扩展
**
1.继承IAnnotationParser接口并重写validate方法,实现自己的校验判断
2.向AnnotationValidator类的vList中添加自己的扩展类
**与mvc框架集成
**
新增拦截器或使用AOP方式获取action的入参,判断是否存在@Validate注解,并根据注解的值判断是返回json数据还是在保存在request作用域中让前端显示
1.在方法的参数中添加@Validate注解
```
@ResponseBody
public Object add(@Validate User user){
}
```
2.新增拦截器或AOP拦截action的参数,注解判断代码:
```
if(field.isAnnotationPresent(Validate.class)){ //判断是否使用了Validate注解
for (Annotation annotation : field.getDeclaredAnnotations()) { //获取所有注解
if(annotation.annotationType().equals(Validate.class) ){ //如果是Validate注解
ValidateResult result = AnnotationValidator.validate(objectRequireEntiry);
if(((Validate)annotation).validType() == ValidType.JSON){
if(!result.isValid()){ //校验失败
//将错误信息以json格式返回给前端
map.put("msg",result.getMessage());
map.put("field",result.getFieldName());
}
}else{
if(!result.isValid()){ //校验失败
//将错误信息保存在qurest作用域中,返回给页面
request.setAttribute("msg",result.getMessage());
request.setAttribute("field",result.getFieldName());
}
}
}
}
}
```