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 注释,但显然这仅适用于字符串。
建议?
I have an object.
public class MyObject
{
....
@Column(name = "a_number") @NotNull @NumberFormat(style = Style.NUMBER) @Min(1)
private Integer aNumber;
...
//getters and setters
}
In my controller I have @Valid annotation on my object being posted. I do have validation working on all my other fields in the class (their all Strings) except this number. If I enter a number from my form it works fine and if I violate the @Min(1) it also gives me the correct validation error. My problem however is that if you enter a string instead of a number it throw a NumberFormatException.
I've seen many examples of Integer and validation but no one accounts for if you enter a string into the form being posted. Do I need to do the validation else where? Javascript? I would like a solution that falls in line with the rest of spring validation so I could use this in other classes. I would just like an error stating it must be numeric. Also I tried using the @Pattern annotation but apparently thats just for strings.
Suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将以下内容添加到控制错误消息的文件中(这些是在类型不匹配的情况下查找的通用消息:
You can add the following to your file which controls your error messages (these are the generic ones it looks for in the case of a type mismatch:
对于那些不明白的人,这里是
spring 4.2.0
中要做的事情。在
WEB-INF>中创建文件名
messages.properties
类文件夹。并将上述类型不匹配消息放入该文件中。在 spring 配置或 servlet.xml 文件中创建以下 bean。
对于问题中的
private Integer aNumber;
等模型属性以及其他验证规则,此规则也适用于类型不匹配转换。您将在此收到您想要的消息。希望它对其他人有帮助。
For those who did not get the idea right here is what to do in
spring 4.2.0
.Create a file name
messages.properties
inWEB-INF > classes
folder. And put the above type mismatch messages in that file.In spring configuration or
servlet.xml
file create the following bean.And for your model attribute like
private Integer aNumber;
in the question along with other validation rules this rule is also applied for type mismatch conversion. You will get your desired message in this.Hope it helps others.
仍然相关,所以我将添加消息源 bean 定义的编程方法:
Still relevant, so I'll add the programmatical approach of message source bean definition: