Form validation with <s:validateAll> ignoring custom validators
lhespanhol Oct 23, 2008 8:43 AMHi all,
I've been trying to validate a form field called ABN (maximum 11 digits) using a customised Hibernate Validator. To do so, I followed the steps below:
(1) Added the <s:validateAll/> tag to my form;
(2) Created a custom Hibernate validator (see code below);
(3) Created a custom annotation for the field constraint to call the above mentioned validator (see code below).
(4) Added the custom tag to the corresponding getter method on my entity.
The corresponding getter method on my entity also contains other annotations for Hibernate constraints, such as @NotNull for instance. But whilst those native annotations are working fine, my custom constraint does not seem to be called whatsoever, even though everythong compiles successfully and no other exception is thrown by the application. It simply does not get called at all.
This is the code for my custom validator:
---------------------------------------------------------------
import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.hibernate.mapping.Property;
import org.hibernate.validator.PropertyConstraint;
import org.hibernate.validator.Validator;
import com.mycompany.Abn;
public class AbnValidator implements Validator<Abn>, PropertyConstraint, Serializable {
public void initialize(Abn abn) {
return;
}
public boolean isValid(Object value) {
Pattern digitPattern = Pattern.compile("^\\d*$");
if (value == null) {
return false;
}
String abn = (String)value;
if (abn.length() > 11) {
return false;
}
Matcher m = digitPattern.matcher(abn);
boolean abnOk = m.matches();
return abnOk;
}
public void apply(Property property) {
return;
}
}
---------------------------------------------------------------
And this is the code for my custom annotation:
---------------------------------------------------------------
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import org.hibernate.validator.ValidatorClass;
import com.mycompany.validator.AbnValidator;
@Documented
@ValidatorClass(AbnValidator.class)
@Target({METHOD, FIELD})
@Retention(RUNTIME)
public @interface Abn {
String message() default "Invalid ABN.";
}
---------------------------------------------------------------
Is there any further configuration necessary in order to make it work? Or any place I should perhaps register my custom validator so that the application is somehow told about its existence? I thought the Hibernate validation could potentially not have been invoked, however that is clearly not the case, since the other annotations (@NotNull, @Length, etc) work fine when added to the getter method.
Any help will be greatly appreciated.
Many thanks,
Luciano