When I try to do a “bind” in my class, it throws an exception, but how can I show an error on the form?
Controller:
@InitBinder
public final void binder(WebDataBinder binder) {
binder.registerCustomEditor(Telefone.class, new PropertyEditorSupport(){
@Override
public void setAsText(String value){
if(null != value){
try{
setValue(Telefone.fromString(value));
} catch (IllegalArgumentException e) {
// what to do here ??
}
}
}
});
public static Telefone fromString(String s) {
checkNotNull(s);
String digits = s.replaceAll("\\D", "");
checkArgument(digits.matches("1\\d{2}|1\\d{4}|0300\\d{8}|0800\\d{7,8}|\\d{8,13}"));
return new Telefone(digits);
}
chekArgument is from Google Preconditions
When phone is not valid, an IllegalArgumentException is thrown .. but how to put it in a BindingResult
I am assuming you are using Java 5 so you can’t use @Valid (no JSR303). If that is the case than the only option is to use BindingResult.
Here is what you can do:
My jsp:
To associate error with specific form, you can use:
Also, BindingResult.reject() associates an error message with the form as a whole. So choose which one works for you. Hope that helps!