What does the @Valid annotation indicate in Spring?
In the following example, the ScriptFile
parameter is marked with an @Valid
annotation.
What does @Valid
annotation do?
@RequestMapping(value = "/scriptfile", method = RequestMethod.POST)
public String create(@Valid ScriptFile scriptFile, BindingResult result, ModelMap modelMap) {
if (scriptFile == null) throw new IllegalArgumentException("A scriptFile is required");
if (result.hasErrors()) {
modelMap.addAttribute("scriptFile", scriptFile);
modelMap.addAttribute("showcases", ShowCase.findAllShowCases());
return "scriptfile/create";
}
scriptFile.persist();
return "redirect:/scriptfile/" + scriptFile.getId();
}
It's for validation purposes.
Validation It is common to validate a model after binding user input to it. Spring 3 provides support for declarative validation with JSR-303. This support is enabled automatically if a JSR-303 provider, such as Hibernate Validator, is present on your classpath. When enabled, you can trigger validation simply by annotating a Controller method parameter with the @Valid annotation: After binding incoming POST parameters, the AppointmentForm will be validated; in this case, to verify the date field value is not null and occurs in the future.
Look here for more info:
http://blog.springsource.com/2009/11/17/spring-3-type-conversion-and-validation/
Adding to above answers, take a look at following. AppointmentForm
's date
column is annotated with couple of annotations. By having @Valid
annotation that triggers validations on the AppointmentForm
(in this case @NotNull
and @Future
). These annotations could come from different JSR-303 providers (e.g, Hibernate, Spring..etc).
@RequestMapping(value = "/appointments", method = RequestMethod.POST)
public String add(@Valid AppointmentForm form, BindingResult result) {
....
}
static class AppointmentForm {
@NotNull @Future
private Date date;
}