2011-11-03 98 views
7

我有一個對象。spring mvc註釋驗證整數

public class MyObject 
{ 
    .... 
    @Column(name = "a_number") @NotNull @NumberFormat(style = Style.NUMBER) @Min(1) 
    private Integer aNumber; 
    ... 
    //getters and setters 
} 

在我的控制器中,我的@Valid註釋在我的對象被張貼。除了這個數字外,我確實在我班的所有其他領域(他們的所有字符串)上進行了驗證。如果我從我的表單中輸入一個數字,它會正常工作,如果我違反了@Min(1),它也會給我提供正確的驗證錯誤。然而,我的問題是,如果你輸入一個字符串而不是一個數字,它會拋出一個NumberFormatException異常。

我見過整數和驗證的很多例子,但是如果你在發佈的表單中輸入一個字符串,沒有人會考慮這個例子。我需要在其他地方進行驗證嗎? JavaScript的?我想要一個符合Spring驗證其餘部分的解決方案,所以我可以在其他類中使用它。我只想說明它必須是數字的錯誤。此外,我嘗試使用@Pattern註釋,但顯然這只是字符串。

對此提出建議?

+1

請參閱http://stackoverflow.com/questions/4082924/jsr-303-type-checking-before-binding – axtavt

+0

謝謝!工作完美!您的帖子從未出現在我的搜索中。 – sauce

回答

9

您可以添加以下到您的文件,它控制你的錯誤消息(這些是通用的那些它的類型不匹配的情況下尋找:

typeMismatch.commandObjectName.aNumber=You have entered an invalid number for ... 
typeMismatch.aNumber=You have entered an invalid number for ... 
typeMismatch.java.lang.Integer=You have input a non-numeric value into a field expecting a number... 
typeMismatch=You have entered incorrect data on this page. Please fix (Catches all not found) 
+0

這正是我所需要的,謝謝! – sauce

3

對於那些誰沒有得到這個想法的權利這裏是在spring 4.2.0做。 在WEB-INF > classes文件夾中創建一個文件名messages.properties,而且把上面的類型不匹配的消息在該文件中。 春天配置或servlet.xml文件創建以下豆。

<beans:bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> 
<beans:property name="basename" value="messages"></beans:property> 
</beans:bean> 

對於您的模型屬性,如private Integer aNumber;與其他驗證規則一起使用,此規則也適用於類型不匹配轉換。你會在這裏得到你想要的信息。

<form:errors path="aNumber"></form:errors> 

希望它能幫助別人。