开发者

Is it too late to handle a Long-Value bound to an Input field by a custom Spring Validator?

开发者 https://www.devze.com 2023-04-03 22:17 出处:网络
Parts of the (Java, Spring-mvc, JSP) Form input is checked by Javascript. The rest is done by a custom Validator.

Parts of the (Java, Spring-mvc, JSP) Form input is checked by Javascript. The rest is done by a custom Validator. The problem is when the Javascript validation is prevented, such an error may be printed:

Failed to convert property value of type java.lang.String to required type java.lang.Long for property xxx; nested exception is java.lang.NumberFormatException: For input string: "x"

Is there a better way to deal with the conversion itself. When the Java-validator runs it already encounters the conversion error - or is there a poss开发者_如何学Pythonibility to check before that?


edit: the code of the Binder within the Controller..

@InitBinder
public void initBinder(WebDataBinder binder) {
   SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
   dateFormat.setLenient(false);

   binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
   binder.registerCustomEditor(Long.class, new CustomNumberEditor(Long.class, true));
}

but its really just standard functionality (org.springframework.beans.propertyeditors.CustomNumberEditor) and I thought there has to be a simple solution, since it seems like a common thing to have a Long Object backing some imput field and trying to get no exception out of it (or catching that one)..


Seems that you need to implement a binder in your controller to convert from String to Long. See if this thread helps, it gives you to code to convert String to Long.

Update

binder.registerCustomEditor(Long.class, "myFieldName", new  PropertyEditorSupprt(){
    @Override
    public void setValue(Object value) {
        if(value instanceof String)
           super.setValue(new Long(value));      
    }

});


if someone's interested .. the code of the custom Binder that worked in the end follows..

  // prevent alphanumeric/special chars in numeric string (for backing field of type Long)
  binder.registerCustomEditor(Long.class, new CustomNumberEditor(Long.class, true) {
     @Override
     public void setAsText(String value) {
        if (value != null && !value.isEmpty() && CustomValidator.isNumeric(value)) {
           super.setAsText(value);
        } else {
           super.setAsText(null);
        }
     }
  });

although, you still have to adjust your validation method so that it makes sense with text that was entered, got removed, and was changed to null!

0

精彩评论

暂无评论...
验证码 换一张
取 消