Java对象验证

验证是编程中众所周知的过程。 例如,假设您要检查提供的对象是否符合某些指定的规则,然后再使用它们或将其持久化到数据库中。 在弹簧例如,包括验证并且可以在应用程序流程的任何阶段使用验证。 我尝试开箱即用,并想象使用java,在类的字段上使用注释或使用指定的条件列表而不使用要验证的类的自定义对象验证。

To do so, I kind of created a repository on github to validate objects.
You can check it over here, any suggestions are welcome.
Start the repo if you like it, and if you want to contribute create a pull/merge request.

Examples of use :

1. Using annotations

假设我们有一个人类,并且对于所有实例,我们都希望分配名字和姓氏,而不要保留空值:

class Person {
    @Validation
    private String name;

    @Validation
    private String lastName;
    // .... other fields...
    // .... getters and setters..
    }

我们将创建一个实例,然后检查它是否有效:

     AnnotationValidator annotationValidator = new AnnotationValidator();
     Person person = new Person();
            person.setName("Mustapha");
            person.setLastName("Belmokhtar");

     boolean isValid = annotationValidator.checkValidation(person);
     ValidationReport validationReportItem = annotationValidator.getValidationReport(person); // gives the details of each field
Result :
   true
  {lastName=|found=String:Belmokhtar, expected={!=null}:[], valid=true|, name=|found=String:Mustapha, expected={!=null}:[], valid=true|}
Validation by Operators:
   class Person{
   // ... others fields 
   @Validation(operator = Operator.GREATER_THAN, value = "18")
    private int age;
    // ... getters and setters ...
    }
     Person person = new Person(); 
     person.setAge(20);

     AnnotationValidator annotationValidator = AnnotationValidator.getInstance();
     boolean isValid = annotationValidator.check(person);
     ValidationReport validationReportItem = annotationValidator.getValidationReport(person);
Result :
   true
   {age=|found=Integer:20, expected={>}:[18], valid=true|}
2.Using criteria :

您也可以使用标准:

        Student student = new Student();
        CriteriaValidator criteriaValidator = CriteriaValidator.getInstance();
        Criteria criteria = new Criteria();
        criteria.setObject(student);
        criteria.add(Criterion.of("name").is("mustapha"));
        criteria.add(Criterion.of("address").notNull());
        criteria.add(Criterion.of("age").greaterOrEquals(4));
        criteria.add(Criterion.of("phoneNumber").matches("\\d{10}"));

        student.setName("mustapha");
        student.setAddress("wall street");
        student.setAge(4);
        student.setPhoneNumber("1234567890");
        System.out.println(criteriaValidator.getValidationReport(criteria));
        assertTrue(criteriaValidator.check(criteria));
Output :
 address=|found=String:wall street, expected={!=null}:[null], valid=true|, phoneNumber=|found=String:1234567890, expected={REGEX}:[\d{10}], valid=true|, name=|found=String:mustapha, expected={==}:[mustapha], valid=true|, age=|found=Integer:4, expected={>=}:[4], valid=true|}
Criteria over complex Objects:

要通过标准对复杂对象执行验证,只需指定所需字段的归档路径,例如:

  class Student {
   // omittd fields for brievety 
    private Matters matters
    //... getters and setters
    }

    //....
      class Matters {
    private double science;
    private double maths;
    private double languages;
    //...
    }
    //... 
Validation process:
  CriteriaValidator criteriaValidator = CriteriaValidator.getInstance();
        Criteria criteria = Criteria.of(student);
        criteria.add(Criterion.of("matters.maths").lessThan(20.0));
        Matters matters = new Matters();
        matters.setMaths(19.99);
        student.setMatters(matters);
        System.out.println(criteriaValidator.getValidationReport(criteria));
        assertTrue(criteriaValidator.check(criteria));

######输出

 {matters.maths=|found=Double:19.99, expected={<}:[20.0], valid=true|}
Validation overs arrays and collections:
class Book {
private int[] isbn; 
private TreeSet<String> keywords;

// .. other fields 
//.. getters and setters
 }
Validation process:
        Book book = new Book();
        CriteriaValidator criteriaValidator = CriteriaValidator.getInstance();
        Criteria criteria = Criteria.of(book);
        criteria.add(Criterion.of("keywords").length(3));
        criteria.add(Criterion.of("isbn").length(11));
        int[] isbn = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
        Set<String> keywords = new TreeSet<>();
        keywords.add("science");
        keywords.add("earth");
        keywords.add("universe");

        book.setKeywords(keywords);
        book.setIsbn(isbn);
System.out.println(criteriaValidator.getValidationReport(criteria));
        assertTrue(criteriaValidator.check(criteria));
Output
 {keywords=|found=TreeSet:[earth, science, universe], expected={length}:[3], valid=true|, isbn=|found=int[]:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], expected={length}:[11], valid=true|}

from: https://dev.to//mustabelmo/java-object-validation-2p9k

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值