This framework implemented get rid of validate bean object using if-else condition and easy to integrate custom validators.
– This is developed using Java 1.5 and no other library is required.
– Used Generics,Reflection and Annotation in implementation.
– Light weight Annotation base bean validation with runtime plugable custom validators.No need to register custom validator it adds automatically at runtime.
– easy to add custom validators.
– It can be use as standalone at presentation layer.
Note: validation annotation applied only to bean property fields.
-In custom validator implementation , add message field to Annotation interface.
You can download code from github(git://github.com/jiren/BeanValidation.git).
Sample bean validation code using this framework.
public class MyBean {
@MaxLength(value = 10, message = "Max length of name field is 10.")
private String name;
@Email(message="Please Enter valid email in format abc@xyz.com")
private String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) {
MyBean myBean = new MyBean();
myBean.setName("name");
myBean.setEmail("abcxyz.com");
//Validation
VMessages vm = BeanValidator.validate(myBean);
//Print Validation Message
for (Iterator it = vm.getMessages().iterator(); it.hasNext();) {
System.out.println(it.next());
}
}
}
=>
Minimum length annotation implementation.Here @AValidation indicate which class going to validate annotated field.It used to identify whether the annotation is validation annotation or not.
@AValidation(validator = com.validation.validators.MinLengthValidator.class)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MinLength {
int value();
String message();
}
=> IValidator interface : Here ‘ T ‘ generic field type which is going to validate using ‘ A’ validation annotation. Here generic interface used to avoid casting object every time for different validators.
public interface IValidator {
public boolean validate(T value, A annotation, VMessages validationMsges);
}
=> Minimum length validator implementation. Here VMessages is store constrain violation messages.
public class MinLengthValidator implements IValidator {
public boolean validate(String value, MinLength aMinLength, VMessages validationMsg) {
if (value != null) {
if (value.length() < aMinLength.value()) {
validationMsg.addMessage(aMinLength.message());
return false;
}
return true;
}
else{
validationMsg.addMessage(aMinLength.message());
return false;
}
}
}
