Reputation: 21
I am trying to validate Employee Request and the validations should be different for post method,put method and delete method
public class Employee {
@NotNull(message = "Employee Id can not be null")
private Integer id;
@Min(value = 2000, message = "Salary can not be less than 2000")
@Max(value = 50000, message = "Salary can not be greater than 50000")
private Integer salary;
@NotNull(message = "designation can not be null")
private String designation;
}
For post method want to validate all the fields present in the request
@PostMapping("/employees")
public ResponseEntity<Void> addEmployee(@Valid @RequestBody Employee newEmployee) {
Employee emp= service.addEmployee(newEmployee);
if (emp== null) {
return ResponseEntity.noContent().build();
}
return new ResponseEntity<Void>(HttpStatus.CREATED);
}
For my put method I want to validate only Salary field and the remaining fields won't be validated
@PutMapping("/employees/{id}")
public ResponseEntity<Vehicle> updateEmployee(@Valid @RequestBody Employee updateEmployee) {
Employee emp= service.EmployeeById(updateEmployee.getId());
if (null == emp) {
return new ResponseEntity<Employee>(HttpStatus.NOT_FOUND);
}
emp.setSalary(updateEmployee.getSalary());
emp.setDesignation(updateEmployee.getDesignation());
service.updateEmployee(emp);
return new ResponseEntity<Employee>(emp, HttpStatus.OK);
}
For delete I don't want to perform any validation
@DeleteMapping("/employees/{id}")
public ResponseEntity<Employee> deleteEmployee(@Valid @PathVariable int id) {
Employee emp = service.getEmployeeById(id);
if (null == employee) {
return new ResponseEntity<Employee>(HttpStatus.FOUND);
}
service.deleteEmployee(id);
return new ResponseEntity<Employee>(HttpStatus.NO_CONTENT);
}
But if I use @Valid all the methods are getting validated with all the fields.
Upvotes: 1
Views: 1158
Reputation: 469
One way to achieve this, is to use @Validated
from org.springframework.validation
library instead of using @Valid
annotation in the method parameters.
By this, you can group your constraints according to your requirements in the model (first group for POST method, second group for PUT method etc.) In the model, you need to use groups
property and specify the name of the group that you want to bind with.
There is a detailed explanation, and giving sample codes about the use of it: here.
Upvotes: 3