New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
My journey to use a validation framework
1. My Journey to Validate Muhammad Saqib Sarwar [email_address]
2. 1.To share my experience(thought process) of choosing a Validator framework. 2.To deliver basic knowledge of my chosen tool. Basic Goals Muhammad Saqib Sarwar [email_address]
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16. Sample Code [Annotated Account Bean] /*--------- Simple Bean ---------------*/ public class Account { @NotEmpty @Length(min=10,max=100) private String accountTitle; @NotEmpty private String processingCode; // regular getters and setters methods } Hibernate Validator Muhammad Saqib Sarwar [email_address]
17. Validation Code: Account account = new Account(); account.setAccountTitle("Mobex Ltd"); ClassValidator<Account> accountValidator = new ClassValidator<Account>(Account.class); InvalidValue[] validationMessages = accountValidator. getInvalidValues (account); for(InvalidValue msg:validationMessages) System.out.println(msg.getPropertyPath()+"-"+msg.getMessage()); OUTPUT accountTitle-length must be between 10 and 100 processingCode-may not be null or empty Hibernate Validator Muhammad Saqib Sarwar [email_address]
18. public class Account { @NotEmpty @Length(min=10,max=100) private String accountTitle; @NotEmpty private String processingCode; // regular getters and setters methods } Hibernate Validator Muhammad Saqib Sarwar [email_address]
19. public class Account { @NotEmpty @Length(min=10,max=100) private String accountTitle; @NotEmpty @ProcessingCode(code=IProcessingCode. CHECK_BALANCE) private String processingCode; // regular getters and setters methods } Hibernate Validator Muhammad Saqib Sarwar [email_address]
20.
21.
22. 2. Constraint Validator Implementation Class public class ProcessingCodeValidator implements Serializable, Validator<ProcessingCode> { private static final long serialVersionUID = 1146464976464879846L; private String code; public void initialize (ProcessingCode parameter) { code = parameter.code(); } public boolean isValid (Object value) { if ( value == null )return false; if (!( value instanceof String)) return false; String str = (String) value; if(str.equals(code)) return true; return false; } } Muhammad Saqib Sarwar [email_address]
23. Account account = new Account(); account.setAccountTitle("Mobex Ltd"); account.setProcessingCode(IProcessingCode. CREDIT_ACCOUNT); ClassValidator<Account> accountValidator = new ClassValidator<Account>(Account.class); InvalidValue[] validationMessages = accountValidator.getInvalidValues(account); for(InvalidValue msg:validationMessages) System. out.println(msg.getPropertyPath()+"-"+msg.getMessage()); OUTPUT accountTitle-length must be between 10 and 100 processingCode-Invalid Processing Code Hibernate Validator Muhammad Saqib Sarwar [email_address]