Tapan
Tapan

Reputation: 187

Validate Bean in Spring boot

Is there a way in spring boot to validate properties in a bean? For Example, consider an Employee Bean consisting of following properties -

  1. id - must start with 01,02,22
  2. Department - Should be any of the one - D1, D2, D3
  3. Name - Must not contain any digits and max length of 10 characters.

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

Answers (1)

Abdullah Tellioglu
Abdullah Tellioglu

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

Related Questions