When I send the request:
"Person": {
"name": 5
}
The request should fail (bad request) because 5 isn't a String. It prints: Person{name='5'}
.
Similarly, there's no error when I send null.
I have these annotations:
@JsonProperty("name")
@Valid
@NotBlank
private String name;
Controller:
public void register(@Valid @RequestBody Person p) {
...
}
How can I make it validate the name so only strings are accepted?
CodePudding user response:
Add a BindingResult
parameter.
public void register(@Valid @RequestBody Person p, BindingResult result) {
if (result.hasErrors()) {
// show error message
}
}
CodePudding user response:
How can I make it validate the name so only strings are accepted?
Use the @Pattern
annotation.
@JsonProperty("name")
@Valid
@NotBlank
@Pattern(regexp="^[A-Za-z]*$", message = "Name should contains alphabetic values only")
private String name;
For more details check this link and this one for the regex.