java 两个日期字段之间的 Spring 验证?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16317207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring Validation Between Two Date Fields?
提问by Java Developer
In my Spring Application, i'm Using Hibernate Validator
for Validation Purpose.
在我的 Spring 应用程序中,我Hibernate Validator
用于验证目的。
When i'm doing simple Validation like @NotEmpty
, @Email
.. i'm easily working
当我做简单的验证时@NotEmpty
,@Email
..我很容易工作
But When coming to Date field, giving Problem...
但是当来到日期字段时,出现问题......
Problem is in my Jsp page i'm getting values type as String then i'm convert String to Date..
问题是在我的 Jsp 页面中,我将值类型作为字符串,然后我将字符串转换为日期..
Hear is my Example...
听说是我的榜样...
@NotEmpty(message = "Write Some Description")
private String description;
private String fromDateMonth;
private String fromDateYear;
private String toDateMonth;
private String toDateYear;
i'm converting this fromDateMonth
and fromDateYear
into Date in this my Controller class.
我正在转换这fromDateMonth
和fromDateYear
成这是我的控制器类Date。
So is their any Possibility to add Validator Annotation in Controller class?
那么他们是否有可能在 Controller 类中添加 Validator Annotation?
Other wise what should i'm do hear? give me suggestions...
否则我应该听什么?给我建议...
回答by kevin847
If you want to validate that fromDate is before toDate, you can write a custom validator to perform this multi-field validation. You write a custom validator, and you also define a custom annotation which is placed on the bean being validated.
如果要验证 fromDate 是否在 toDate 之前,可以编写自定义验证器来执行此多字段验证。您编写了一个自定义验证器,并且还定义了一个放置在要验证的 bean 上的自定义注释。
See the following answers for more information.
有关更多信息,请参阅以下答案。
回答by Romain R
For sure you can use Bean Validation inside your controller, just add an annotation on the property like you did in your model. But the best way would be use a Date type in your model instead of string.
确保您可以在控制器中使用 Bean 验证,只需像在模型中一样在属性上添加注释即可。但最好的方法是在模型中使用 Date 类型而不是字符串。