Susie
Susie

Reputation: 5138

Type mismatch, Spring BindException

When I input alphabets such as "adsf" in the input field, spring tries to bind it to my price( a double) property of my "Code" object and this causes the bind exception. What can I do to avoid this error, if I wanted to keep the field as a double?

POJO

@entity
@Table(name=“CODE”)
public class Code{

    @Column(name=“PRICE”)
    @NotNull
    @DecimalMax(value=“999999999999.999999”)
    @DemimalMin(value=“0.0”)
    private Double price;

    //getters and setters

}

My controller

@RequestMapping(value=“validateField”, method=RequestMethod.POST, produces=“application/json”)
public FieldValidatinResult validateField(final Code code, final String field){
    //return statement
}

html page

<input type=“text” class=“form-control validatable” id=“price”></input>

Error message:

    Field error in object ‘code’ on field ‘price’: rejected value [adsf]; 
codes[typeMismatch.code.price,typeMismatch.price,typeMismatch.java.lang.Double,typeMismatch]; arguments[org.springframework.context.support.DefaultMessageSourceResolvable: 
codes [code.price,price]; arguments []; default message [price]]; default message 
[Failed to convert property value of type 'java.lang.String' to required type 
'java.lang.Double' for property 'price'; nested exception is 
java.lang.NumberFormatException: For input string: "adsf"]

Upvotes: 1

Views: 4975

Answers (2)

rocky
rocky

Reputation: 5004

I would not say that validations on client side are 'best' as they can be easily avoided ( take action url from form, post some garbage ), but its probably the easiest to do.

I would recommend to add validation also on server side. You have your annotations ready, now you have to use @Valid on your Code code and BindingResult parameter. http://codetutr.com/2013/05/28/spring-mvc-form-validation/ <- this seems to be some useful tutorial.

Upvotes: 1

Aniket Thakur
Aniket Thakur

Reputation: 68935

Error clearly says

[Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Double' for property 'price'; nested exception is java.lang.NumberFormatException: For input string: "adsf"]

User has provided a non number input and when it is parsed as double on server it is throwing NumberFormatException. Best way to solve this is to handle it client side. Add a validation like below before submitting the form

if (!isNaN(parseInt($("#price").val()))) {
    //proceed with form submit
}

Upvotes: 0

Related Questions