Reputation: 187
Is there a way in spring boot to validate properties in a bean? For Example, consider an Employee Bean consisting of following properties -
I can have a separate method and validate the bean every time but looking for some better way to implement this using spring boot.
Upvotes: 1
Views: 292
Reputation: 1464
You could use spring boot validation to validate your patterns. Add this dependency to your gradle file implementation('org.springframework.boot:spring-boot-starter-validation') https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-validation checkout the latest version
class Employee {
@Pattern(regexp = "^(01|02|22).+$")
private String id;
@Size(max = 10)
@Pattern(regexp = "^[^0-9]+$")
private String name;
@Pattern(regexp = "^D[1-3]$")
private String department;
}
And in your request
@RestController
class EmployeeRequest {
@PostMapping("/registerEmployee")
ResponseEntity<String> registerEmployee(@Valid @RequestBody Employee employee) {
return ResponseEntity.ok("valid");
}
}
Note: I am not sure about syntax of regex but you should define your regex for your business requirements.
Upvotes: 5