I have a form class like this:
public class ProjectForm {
@NotEmpty
private String name;
@NotEmpty
private String desription;
// getters and setters
}
this form is used to both create and edit Project objects which will be saved in a database.
I have two different controllers for creating and editing project objects.
@PostMapping("/projects/edit/{id}")
public String editProject(@Valid ProjectForm projectForm, BindingResult bindingResult, @PathVariable("id") String id) {
//Controller code here
}
and
@PostMapping("/projects/new")
public String addProject(@Valid ProjectForm projectForm, BindingResult bindingResult) {
//Controller code here
}
As you see, both controllers use the ProjectForm class. How can I make the name field for the first controller mandatory and for the second one optional?
You named both of your methods as editProject but I assume only the first one is for editing. As a solution, you can create another class just for editing without using @NotEmpty annotation say, ProjectFormWrapper. Other than that, if you are editing an object don't use POST, use PUT.
Yes u can do it using validation-groups.see this docs validation-groups-docs
public interface FirstValidation{
}
public class ProjectForm {
@NotEmpty(groups = {FirstValidation.class},message = "Name can not be empty")
private String name;
@NotEmpty
private String desription;
// getters and setters
}
@PostMapping("/projects/edit/{id}")
public String editProject(@Validated(FirstValidation.class) ProjectForm projectForm, BindingResult bindingResult, @PathVariable("id") String id) {
//Controller code here
}
@PostMapping("/projects/new")
public String addProject(@Valid ProjectForm projectForm, BindingResult bindingResult) {
//Controller code here
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.