I'm trying to see if I can use custom validators for any type of validation task I need. The only task that fails with what I know so far is validation that requires more than one field... I"m not sure how to do this.
Ok, so to practice I decided to try and make a StringMatch validator (though one that could match any datatype would be nice.)
I'm not sure how to send a field name as a string, from an entity bean, then get the actual value for it. How do I get information from more than one field into a validator?
Here's what I've got so far... it's based on the Capitalized example from the hibdocs (which is all buggy and broken and took some work to figure out btw :P)
Anyway, just some direction on how to do complex things with custom annotations would be great. I'm having a hard time finding anything beyond the basic examples.
Code:
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import org.hibernate.validator.ValidatorClass;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
@ValidatorClass(CapitalizedValidator.class)
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface StringMatch {
String field();
String message() default ""does not match";
}
Code:
import org.hibernate.mapping.Property;
import org.hibernate.validator.PropertyConstraint;
import org.hibernate.validator.Validator;
public class StringMatchValidator implements Validator<StringMatch>,
PropertyConstraint {
private String field;
// part of the Validator<Annotation> contract,
// allows to get and use the annotation values
public void initialize(StringMatch parameters) {
field = parameters.field();
}
// part of the property constraint contract
public boolean isValid(Object value) {
if (value == null)
return true;
if (!(value instanceof String))
return false;
String string = (String) value;
if(string.equals(field)) //field is just a string here... how do I get a value from the entity bean using just a string?
{
return true;
}
return false;
}
public String field(){
return field;
}
public void apply(Property arg0) {
// TODO Auto-generated method stub
}
}