0

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?

Tom1998
  • 55
  • 1
  • 6

2 Answers2

0

Add a BindingResult parameter.

public void register(@Valid @RequestBody Person p, BindingResult result) {
    if (result.hasErrors()) {
        // show error message
    }
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • I have nested classes and I want to validate a field in the child class. It says there are 0 errors (result.hasErrors() returns false). I put ```@Valid``` and ```@NotBlank``` on the field in the child class, and I put ```@Valid``` on the Child child; field in the Parent class. Note that it should return an error because 5 is not a String, it's a number. The person object is the child class. – Tom1998 Jan 20 '23 at 19:45
  • @Tom1998 You may need to create your own `ObjectMapper` bean: `new ObjectMapper().disable(MapperFeature.ALLOW_COERCION_OF_SCALARS)` – Unmitigated Jan 20 '23 at 20:05
0

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.

Harry Coder
  • 2,429
  • 2
  • 28
  • 32
  • But this only validates a string. For example, "5" would be a valid name if I use @Pattern. Since the request from the front end has an integer 5 (not the String 5) it should fail. – Tom1998 Jan 20 '23 at 19:38
  • Have you tried? – Harry Coder Jan 20 '23 at 19:50
  • Yes, please see my other comment below about the parent/child classes. Person is a child class so really the request looks like ```{"Person": { "name": 5 }}``` – Tom1998 Jan 20 '23 at 19:53
  • Can you post the person object? – Harry Coder Jan 20 '23 at 19:55
  • ```public class Person { @JsonProperty("name") @Valid @NotBlank(message = "failure") @Pattern(regexp="^[A-Za-z]*$", message = "Name should contains alphabetic values only") private String name; }``` public class Parent { @JsonProperty("Person ") @Valid private Person person; } – Tom1998 Jan 20 '23 at 20:01