2

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 ??
                }
            }
        }

    });

Phone:

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

Falci
  • 1,823
  • 4
  • 29
  • 54
  • 1
    Check out [this discussion](http://stackoverflow.com/questions/691790/spring-validation-how-to-have-propertyeditor-generate-specific-error-message) – Usha Jan 16 '13 at 16:49

1 Answers1

6

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:

@Controller
public class MyController {

    @RequestMapping(method = RequestMethod.POST, value = "myPage.html")
    public void myHandler(MyForm myForm, BindingResult result, Model model) {
        result.reject("field1", "error message 1");
    }
}

My jsp:

<form:form commandName="myForm" method="post">
<label>Field 1 : </label>
<form:input path="field1" />
<form:errors path="field1" />

<input type="submit" value="Post" />
</form:form>

To associate error with specific form, you can use:

result.rejectValue("field1", "messageCode", "Default error message");

Also, BindingResult.reject() associates an error message with the form as a whole. So choose which one works for you. Hope that helps!

Hardik Gajjar
  • 1,024
  • 12
  • 27
slashdot
  • 766
  • 5
  • 11