4

I have entity:

public class User{
   @NotNull
   private Integer age;
} 

In Restcontroller:

@RestController
public UserController {
 ..... 
} 

I have BindingResult, but field age Spring doesn't validate. Can you tell me why?

Thanks for your answers.

Ondra Pala
  • 59
  • 1
  • 1
  • 2

2 Answers2

10

If your posting something like JSON data representing the User class you can use the annotation @Valid in conjunction with @RequestBody to trigger validation of annotations such as the @NotNull you have on your age property. Then with BindingResult you can check if the entity/data has errors and handle accordingly.

@RestController
public UserController {

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<?> create(@Valid @RequestBody User user, BindingResult bindingResult) {
        if(bindingResult.hasErrors()) {
            // handle errors
        }
        else {
            // entity/date is valid
        }
    }
}

I'd make sure your User class also has the @Entity annotation as well.

@Entity
public class User {
    @NotNull
    @Min(18)
    private Integer age;

    public Integer getAge() { return age; }

    public setAge(Integer age) { this.age = age; }
}

You may want to set properties to output/log SQL so that you can see that the proper restraints are being added to the User table.

Hopefully that helps!

Alexander Staroselsky
  • 37,209
  • 15
  • 79
  • 91
  • Thanks for your answers, I do it, like you, but @NotNull on Integer attribute age not validation, but every for example String attribute works fine. – Ondra Pala Jan 19 '17 at 19:11
  • 2
    Try adding the validation annotation `@Min(1)` or `@Range(min=1, max=10000)` to the `Integer` age property and see if it successfully validates. – Alexander Staroselsky Jan 19 '17 at 19:14
  • Yes, Thanks, I try it. But It is strange. On this tutorial: https://spring.io/guides/gs/validating-form-input/ use @NotNull annotation on Integer attribute – Ondra Pala Jan 19 '17 at 19:21
  • 1
    Great to hear! I think @RestController needs the `@Min` or `@Range` because your data is coming in via JSON as a `String` for the `age` property. Try getting the JSON to send as a number instead if you can and `@NotNull` might be all you need. In the example the form the age field has a bean-backed property so it must be converting to a number on submit. The @Min or @Range implicitly converts to a number type when doing the check. Adding a `@Range` to something like age would make sense though as you wouldn't want user to enter age 999. Please mark answer that help you solve the issue. Thanks! – Alexander Staroselsky Jan 19 '17 at 19:29
1

If needed you can specifiy default messages

@NotNull("message": "age: positive number value is required")

@Min(value=18, message="age: positive number, min 18 is required")

and please use dto's

Suvarna
  • 165
  • 1
  • 8