skip to Main Content

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?

2

Answers


  1. Add a BindingResult parameter.

    public void register(@Valid @RequestBody Person p, BindingResult result) {
        if (result.hasErrors()) {
            // show error message
        }
    }
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search