verifier
一个自由简单的 Java 校验工具,支持代码编写和注解方式,支持 Springboot 集成。
简单使用案例
文本校验
示例:
VerifierBuilder verifierBuilder = new VerifierBuilder();
String bookName = "";
String author = "";
Verifier verifier = verifierBuilder
// 配置校验器,默认名称为类名简称 TextVerifier
.addVerifier(new TextVerifier())
// 配置自定义名称的校验器
.addVerifier("myTextVerifier", new TextVerifier())
.warningFormat("myTextVerifier", "%s必填!")
// 用TextVerifier校验 bookName字段
.add("TextVerifier", "bookName", "书名", bookName)
// 用myTextVerifier校验 author字段
.add("myTextVerifier", "author", "作者", author)
.build();
VerifyResult verifyResult = verifier.verify();
logger.info(verifyResult.toString());
Assert.assertTrue(verifyResult.hasWarning());
结果:
{key='author', subject='作者', warning='作者必填!'}
{key='bookName', subject='书名', warning='书名校验失败'}
正则文本校验
示例:
VerifierBuilder verifierBuilder = new VerifierBuilder();
// 自定义日期校验
DateTextVerifier myDateTextVerifier = new DateTextVerifier();
myDateTextVerifier.setPattern("[1-2]\\d{3}\\d{2}\\d{2}");
// 自定义正则校验
TextRegexVerifier webSiteVerifier = new TextRegexVerifier(new ArrayList<>(), "http[s]?://www..*.com");
Verifier verifier = verifierBuilder
// 日期校验,默认 yyyy-MM-dd
.addVerifier(new DateTextVerifier())
.addVerifier("myDateVerifier", myDateTextVerifier)
.addVerifier("webSiteVerifier", webSiteVerifier)
.warningFormat("webSiteVerifier","%s格式不正确")
.add("DateTextVerifier", "publicationDate2", "出版日期2", "2020-01-01")
.add("DateTextVerifier", "publicationDate3", "出版日期3", "2020-011-011")
.add("myDateVerifier", "publicationDate4", "出版日期4", "2020-01-01")
.add("myDateVerifier", "publicationDate6", "出版日期6", "90200101")
.add("webSiteVerifier", "webSite", "网站", "https://www.baidu.cn")
.build();
VerifyResult verifyResult = verifier.verify();
logger.info(verifyResult.toString());
Assert.assertTrue(verifyResult.hasWarning());
结果:
{key='publicationDate3', subject='出版日期3', warning='出版日期3校验失败'}
{key='publicationDate4', subject='出版日期4', warning='出版日期4校验失败'}
{key='publicationDate6', subject='出版日期6', warning='出版日期6校验失败'}
{key='webSite', subject='网站', warning='网站格式不正确'}
数字校验
示例
VerifierBuilder verifierBuilder = new VerifierBuilder();
Verifier verifier = verifierBuilder
.addVerifier(new NumberVerifier())
.add("NumberVerifier", "price", "价格", null)
.build();
VerifyResult verifyResult = verifier.verify();
logger.info(verifyResult.toString());
Assert.assertTrue(verifyResult.hasWarning());
结果
{key='price', subject='价格', warning='价格校验失败'}
选择校验(单选和多选)
示例:
VerifierBuilder verifierBuilder = new VerifierBuilder();
Verifier verifier = verifierBuilder
// 单选
.addVerifier(new SelectVerifier())
// 多选
.addVerifier(new MultipleSelectVerifier())
.add("SelectVerifier", "classify", "分类", "散文", (SelectVerifierOptionsFunction) () -> {
List<String> options = new ArrayList<>(2);
options.add("小说");
options.add("诗歌");
return options;
})
.add("MultipleSelectVerifier", "hobbies", "爱好", new ArrayList<String>() {{
add("打篮球");
add("踢足球");
add("打游戏");
}}, (SelectVerifierOptionsFunction) () -> {
List<String> options = new ArrayList<>(2);
options.add("打篮球");
options.add("踢足球");
options.add("睡觉觉");
return options;
})
.build();
VerifyResult verifyResult = verifier.verify();
logger.info(verifyResult.toString());
Assert.assertTrue(verifyResult.hasWarning());
结果:
{key='classify', subject='分类', warning='分类选项非法'}
{key='hobbies', subject='爱好', warning='爱好选项非法'}
自定义校验器
示例:
VerifierBuilder verifierBuilder = new VerifierBuilder();
Verifier verifier = verifierBuilder
.addVerifier("myVerifier", new AbstractVerifier() {
@Override
public Optional<VerifyResponse> test(VerifyItem verifyItem) {
// 自定义校验逻辑
return Optional.of(new VerifyResponse(verifyItem.getKey(), verifyItem.getSubject(), "任何信息都是错误的"));
}
})
.add("myVerifier", "key", "subject", "12345")
.build();
VerifyResult verifyResult = verifier.verify();
logger.info(verifyResult.toString());
Assert.assertTrue(verifyResult.hasWarning());
结果
{key='key', subject='subject', warning='任何信息都是错误的'}
基于注解方式
编写需要校验的对象类,省略了set
和get
方法
@VerifyObject({
// 配置校验器,未指定名字,默认是简单类名
@VerifierConfig(verifier = TextVerifier.class),
@VerifierConfig(verifier = DateTextVerifier.class),
@VerifierConfig(verifier = CollectionVerifier.class),
@VerifierConfig(verifier = SelectVerifier.class),
@VerifierConfig(verifier = MultipleSelectVerifier.class),
// 指定校验器类型和名字还有警告格式
@VerifierConfig(verifier = TextVerifier.class, name = "myTextVerifier",warningFormat = "我的自定义校验%s未通过"),
@VerifierConfig(verifier = NumberVerifier.class),
})
// 可继承父类的成员变量,并校验
public class BookForm extends BaseForm{
// 定义校验主题,可设置多个,如果校验失败会产生多条校验失败的记录
// 指定通过verifier、verifyIndex或者verifierName指定校验器
@VerifySubject(subject = "bookName", verifier = TextVerifier.class)
@VerifySubject(subject = "书名", verifyIndex = 0)
private String bookName;
@VerifySubject(verifierName = "myTextVerifier")
private String author;
@VerifySubject(subject = "publicationDate", verifyIndex = 1)
private String publicationDate;
@VerifySubject(subject = "代理商", verifyIndex = 2)
private Collection<String> proxy;
@VerifySubject(subject = "分类", verifyIndex = 3)
// 定义可选项
@SelectionOptions({"小说", "诗歌", "散文"})
private String classify;
@VerifySubject(subject = "分类2", verifyIndex = 4)
@SelectionOptions({"小说", "诗歌", "散文"})
private List<String> classify2;
}
public class BaseForm {
@VerifySubject(subject = "id", verifier = NumberVerifier.class)
private Integer id;
}
校验示例:
BookForm bookForm = new BookForm();
ArrayList<String> proxy = new ArrayList<>();
proxy.add("代理商1");
bookForm.setProxy(proxy);
bookForm.setClassify("杂志");
bookForm.setClassify2(new ArrayList<>());
VerifierBuilder verifierBuilder = new VerifierBuilder();
Verifier verifier = verifierBuilder.verifyObject(bookForm)
.build();
VerifyResult verifyResult = verifier.verify();
logger.info(verifyResult.toString());
Assert.assertTrue(verifyResult.hasWarning());
结果:
{key='publicationDate', subject='publicationDate', warning='publicationDate校验失败'}
{key='author', subject='author', warning='我的自定义校验author未通过'}
{key='classify', subject='分类', warning='分类选项非法'}
{key='bookName', subject='bookName', warning='bookName校验失败'}
{key='bookName', subject='书名', warning='书名校验失败'}
{key='id', subject='id', warning='id校验失败'}
和 Spring Boot 集成
具体使用参见SpringBoot集成案例
-
配置
application.yml
verifier: # 默认使用 @TargetVerifyMethod 拦截,可自定义 target-verify-method: com.qingcha.verifier.spring.TargetVerifyMethod # 只校验@Service类,可以自定义 target-verify-class: org.springframework.stereotype.Service # 拦截顺序 order: 1234
-
启动类添加注解
@SpringBootApplication @EnableVerifier public class ExampleApplication { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(ExampleApplication.class); StudentService studentService = context.getBean(StudentService.class); Student student = new Student(); student.setGrade("六年级"); student.setHobbies(Collections.singletonList("睡觉")); studentService.addStudent(student); } }
-
编写自定义校验回调
@Component public class ExampleVerifierWarningCallback implements VerifierWarningCallback { @Override public void finallyWarningCallback(VerifyResult verifyResult) throws Throwable { // 此处如果不满足校验条件,可以抛出异常终止操作 System.out.println(verifyResult); } }
-
指定拦截方法
@Service public class StudentServiceImpl implements StudentService { @TargetVerifyMethod @Override public String addStudent(Student student) { return student.getName(); } }
-
结果
{key='grade', subject='年级', warning='年级选项不合法'} {key='name', subject='姓名', warning='姓名必填'} {key='hobbies', subject='爱好', warning='爱好选项非法'}