Back Forum Reply New

How to Resolve Error before Validation

Hi Guys,

I have html form, now on its command object one of its field is a float datatype.
On loading of the form what the user will see on the browser, that column will have a default value of 0. Got it from the initialization of the command object I assume. Now if the user removes the 0.00 value in the html input element and submits the form I get this error...

Failed to convert property value of type [java.lang.String] to required type [float] for property 'pricePerMonth'; nested exception is java.lang.NumberFormatException: empty String

How can I trap this and just return a validation error?

TIA!
Richard

I think the error is thrown here...

protected final ServletRequestDataBinder bindAndValidate(fromServletRequest request, Object command)
throws Exception {

ServletRequestDataBinder binder = createBinder(request, command);
BindException errors = new BindException(binder.getBindingResult());
if (!suppressBinding(request)) {
binder.bind(request);

You will need to write your own custom property editor and override the initBinder method in the controller.

This is an example of a custom Integer property editor:

public class CustomIntegerPropertyEditor extends PropertyEditorSupport {

public CustomIntegerPropertyEditor() {
}

public String getAsText() {
Integer i = (Integer) getValue();
if(i == null){
return quot;quot;;
}
return i.toString();
}

public void setAsText(String str) {
try {
setValue(new Integer(str));
} catch (NumberFormatException nfe) {
setValue(new Integer(0));
}
}
}and in your controller:protected void initBinder(fromServletRequest request,
ServletRequestDataBinder binder) throws Exception {
binder.registerCustomEditor(Integer.class, new CustomIntegerPropertyEditor());
super.initBinder(request, binder);
}

This might be simpler...

showthread.php?t=28972

Thanks. I will try them and update this thread.

For some reasons this is not working for me.Originally Posted by craigchapman1975This might be simpler...

showthread.php?t=28972

Originally Posted by Ric.hardFor some reasons this is not working for me.

Make sure you register right type of PropertyEditor (in initBinder-method).

Hi All,

I made a simple workaround by making all my command class attribute String.

Richard
¥
Back Forum Reply New