Difference between them
|
@Valid |
@Validated |
standard |
Standard JSR-303 |
Enhance JSR-303 specification |
package |
javax.validation |
org.springframework.validation |
Verification results |
BindingResult result |
BindingResult result |
Group support |
I won't support it |
Support |
Packet sequence |
I won't support it |
Support |
type annotation |
? |
Support |
Method annotation |
Support |
Support |
Method Parameter annotation |
Support |
Support |
Constructor comment |
Support |
? |
Member attribute annotation |
Support |
I won't support it |
Nested validation |
Support |
I won't support it |
Group example
public interface First{}
public interface Second{}
public class User {
// All verified
@NotNull(message = "...")
private int id;
// First to verify
@NotNull(message = "...", groups = { First.class })
private String username;
// First or Second to verify
@NotNull(message = "...", groups = { First.class, Second.class })
private String content;
// First verify NotEmpty, Second verify Size
@NotEmpty(message = "...", groups = { First.class })
@Size(message = "...", min = 3, max = 8, groups = { Second.class })
private String height;
}
// Verify only Second grouping and ungrouped properties
public String save(@Validated( { Second.class }) User user, BindingResult result) {
if (result.hasErrors()) {
return "validate/error";
}
return "redirect:/success";
}
Packet sequence
public interface GroupA {}
public interface GroupB {}
@GroupSequence( { GroupA.class, GroupB.class })
public interface Group {}
public @ResponseBody String save(@Validated({ Group.class }) User user, BindingResult result) {
if(result.hasErrors()) {
return false;
}
return true;
}
Nested validation
public class Item {
@NotNull(message = "id Can not be empty")
@Min(value = 1, message = "id Must be a positive integer")
private Long id;
@Valid
@NotNull(message = "props Can not be empty")
@Size(min = 1, message = "At least one attribute is required")
private List<Prop> props;
}
public class Prop {
@NotNull(message = "pid Can not be empty")
@Min(value = 1, message = "pid Must be a positive integer")
private Long pid;
@NotNull(message = "vid Can not be empty")
@Min(value = 1, message = "vid Must be a positive integer")
private Long vid;
@NotBlank(message = "pidName Can not be empty")
private String pidName;
@NotBlank(message = "vidName Can not be empty")
private String vidName;
}
@RestController
public class ItemController {
@RequestMapping("/item/add")
public void addItem(@Validated Item item, BindingResult bindingResult) {
doSomething();
}
}
Validate multiple objects
@Controller
public class PeopleController {
@RequestMapping("/add")
public @ResponseBody String add(@Validated People pp, BindingResult result1, @Validated Person ps, BindingResult result2)
{
if(result1.hasErrors())
{
return false;
}
if(result2.hasErrors())
{
return false;
}
return true;
}
}