Reputation: 43
I want to do a custom validations using spring boot for below method.I want to validate "id" if it is other than a to z, 0 to 9 and - then I want to set error message and pass that in ResponseEntity.
@RestController
public class DataController {
@Autowired DataService dataService;
@RequestMapping("/data/{id}")
public ResponseEntity<Data> getData(@PathVariable String id)
{
Data messages = dataService.getData(id, Data.DataFormat.ALL);
return new ResponseEntity<>(messages, HttpStatus.OK);
}
Upvotes: 1
Views: 2202
Reputation: 9447
Another solution: You can use @Pattern and don't forget to use @Validated before your class.
@RestController
@RequestMapping("required url")
@Validated
public class yourClassName{
@RequestMapping("/data/{id}")
public ResponseEntity<Data> getData(@Valid @Pattern(regexp = "^[a-z0-9\\-]+$",message = "Your custom message") @PathVariable String id){
Data messages = dataService.getData(id, Data.DataFormat.ALL);
return new ResponseEntity<>(messages, HttpStatus.OK);
}
}
Upvotes: 1
Reputation: 18235
You can't validate a single primitive type in parameter automatically.
You have to validate it manually.
Try this:
private static final Pattern ACCEPTED_CHARACTERS = Pattern.compile("^[a-z0-9\\-]+$");
@RequestMapping("/data/{id}")
public ResponseEntity<Data> getData(@PathVariable String id)
{
if (!ACCEPTED_CHARACTERS.matcher(id).matches()) {
return new ResponseEntity<>("Your messge", YOUR CODE);
}
Data messages = dataService.getData(id, Data.DataFormat.ALL);
return new ResponseEntity<>(messages, HttpStatus.OK);
}
In real app, the test for pattern should be done in an utility class
Upvotes: 2