my journey to use a validation framework
TRANSCRIPT
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 protected]
• New Change Arrived in current project
•DB Fields From 11 to 137•Account [54 Fields] Customer [74 Fields] Customer_account[9 Fields]•So Big Change on Message Validations• For: Create an Account Message
•Total: 46 Fields•14 Mandatory Fields
•13 have length checks•5 have pattern checks
•others if exist should be validated too ….
How I felt the need ?
Simply Means a huge collection
of if-else statements
Muhammad Saqib Sarwar [email protected]
•1st I written required if-else statements.
•BUT Soon
I Found
Myself
In huge
Mess ..
How I felt the need ?
Muhammad Saqib Sarwar [email protected]
•Asked the BOSS•Google “how to avoid too many if-else”•Placed Question on JavaRanch•Consulted with Colleagues
Surprised !•Business layer validation frameworks
exist in java world•I only know them as presentation
layer validator.
What I did next …
Muhammad Saqib Sarwar [email protected]
•There are many available like•Spring’s own validation•Commons Validator•JaValid•Hibernate Validator (My Chosed One)•And many more …
•Now the Question is
Which one to use ?•So I Sorted Few Priorities
•It should Solves the problem•It should have Short learning curve
Which one to use ..?
Muhammad Saqib Sarwar [email protected]
•First I looked at Validation in Spring 2.0.8 (as we already using it)•Two Parts in the Validation Package
•Validator Interface Implementation•DataBinder
•Primarily used in Spring-MVC framework•Have to implement complete validation logic in validate() method•Separate Validator for each entity•Not fallow any standard (like few emerging in the market)
Validation in Spring 2.0.8
Muhammad Saqib Sarwar [email protected]
•Validation of JavaBeans based on an xml file•Provides two distinct sets of functionality
1. A configurable (typically XML) validation engine
2. Reusable "primitive" validation methods
Steps– Create XML file– Instantiate Validator class
(org.apache.commons.validator.Validator)
– Add Resources (JavaBean,Locale)– Call Validator’s validate method– Evaluate Results
Commons Validator
Muhammad Saqib Sarwar [email protected]
•Heavily depends on XML•Manual evaluation of errors []•No default error messages•Lengthy validation code•Fallow No Standard
Commons Validator
Muhammad Saqib Sarwar [email protected]
•I want something easier than XML so searched for Annotation based bean validation frameworks and found JaValid.org•It is an Annotations based bean validation framework•Could be used standalone•Provides full integration with Spring, JSF, Facelets and DB•Customizable and Extensible•Built in annotations for basic validations•Well elaborated documentation•Well documented source code
Muhammad Saqib Sarwar [email protected]
1. Annotate Bean’s Properties/(getter Methods)
2. Instantiate Validator implementation
3. Pass bean instance to Validator
4. Validator returns List<ValidationMessage>
Steps to use JaValid
Muhammad Saqib Sarwar [email protected]
• only few built in annotation constraints• building new constraints are little lengthier• use XML configuration file to know about annotation classes and their related validator classes.• error messages are hard coded• ValidationMessage object is not customizable• does not fallow any standard for validation
Few disadvantages of JaValid !
Good Solution but not as simple and easy as hibernate validator
Muhammad Saqib Sarwar [email protected]
•Annotations based bean validation framework•Aims to provide implementation of the emerging standard (JSR - 303 Bean Validation)•Purely intended for multi-layered data validation•Constraints are expressed in a single place (model)•Not limited to use with hibernate
•Can be used any where in application•Can be used with any java persistence provider
Hibernate Validator
Muhammad Saqib Sarwar [email protected]
•Decent Collection of Built in Constraints
•@Length (min=,max=)•@Max(value=)•@Min(value=)•@NotNull•@NotEmpty•@Past•@Future•@Size(min=, max=)
Hibernate Validator
•@Pattern(regex="regexp”, flag=)
•@Range(min=, max=)•@AssertFalse•@AssertTrue•@Valid•@Email•@CreditCardNumber•@Digits•@EAN•Few more …
Muhammad Saqib Sarwar [email protected]
•Error Messages• Validator returns array of InvalidValue • InvalidValue contains constraint violation information (bean, name, path, value etc)• It also contains Error Description Message• we can override Error Messages
• By Creating Own ValidatorMessages.properties• we can embed constraint parameters in messages
Hibernate Validator
Muhammad Saqib Sarwar [email protected]
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 protected]
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 protected]
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 protected]
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 protected]
Steps For Writing Our Own Constraints1. Constraint Descriptor (annotation)
2. Constraint Validator (implementation class)
Hibernate Validator
Muhammad Saqib Sarwar [email protected]
1. Constraint Descriptor (annotation)
@Documented
@ValidatorClass(ProcessingCodeValidator.class)
@Target({METHOD, FIELD})
@Retention(RUNTIME)
public @interface ProcessingCode {
String code();
String message() default "Invalid Processing Code";
}
Hibernate Validator
org.hibernate.validator.ValidatorClass
Muhammad Saqib Sarwar [email protected]
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 protected]
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 protected]
Using the Validator1. Database Schema-Level Validation
2. ORM Integration1. Hibernate event-based validation
– PreInsertEvent– PreUpdateEvent
2. Java Persistence event-based validation
3. Application-level validation
4. Presentation layer validation
Hibernate Validator
Muhammad Saqib Sarwar [email protected]
Benifits• simplicity
•Avoid XML based configuration•Could be learned in short time•Could be implemented in minutes
•Constraints annotation could be applied to•Property•Getter method•Bean Class
•Aims to Fallows a developing standard (JSR-303 Bean Validation)•Fallows DRY Principle [multi-layered validation]• etc [many more to explore]
Muhammad Saqib Sarwar [email protected]
•We Use Validation Framework•To avoid series of messy if-else statements•To Increase code readability•To make code easily maintainable•To avoid writing validation on multiple layers•To increase productivity
Summary
Muhammad Saqib Sarwar [email protected]