user11338912
user11338912

Reputation:

@valid annotation is not working in spring boots

I'm using spring boot to build API, in post request I use Valid notation to validate user input that is posted as JSON file, however when I test it by leaving some fields empty they are still passed. I'm not sure why since I'm using valid notation before the object argument.

what can be wrong?

Object class


    @NotNull(message = "Please provide a name")
    private String name;

    @NotNull(message = "Please provide a gender")
    private Gender gender;

    @NotNull(message = "Please provide a birthDay")
    private String birthDay;

    @NotNull(message = "Please provide a latitude")
    private double latitude;

    @NotNull(message = "Please provide a longitude")
    private double longitude;

    public Wolf(String id, @NotNull String name, @NotNull Gender gender, @NotNull String birthDay, @NotNull double latitude, @NotNull double longitude)
    {
        this.id = id!=null ? id : UUID.randomUUID().toString();
        this.name= name;
        this.gender= gender;
        this.birthDay= birthDay;
        this.latitude= latitude;
        this.longitude= longitude;
    }

rest-controller class

@Autowired
    private Wolf_Service wolf_service;

    @RequestMapping("Wolf/wolf_list")
    public List<Wolf> All_wolfs()
    {
        return wolf_service.display_wolf_list();
    }
  @PostMapping(value = "Wolf/createwolf", consumes = "application/json", produces = "application/json")
    public Wolf createwolf (@Valid @RequestBody Wolf wolf)   {
        
        var isAdded =  wolf_service.add_wolf(wolf);
        if (!isAdded) {
            return null;
        }
            return wolf;
    }

Upvotes: 0

Views: 2531

Answers (3)

Ali Zedan
Ali Zedan

Reputation: 283

Check that you import correctly from Validation.Constraints not from com.sun.istack.

import javax.validation.constraints.NotNull;

If that not fix your problem. Check your pom.xml, if you have used validation dependency.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Upvotes: 0

Amit kumar
Amit kumar

Reputation: 2724

This issue often comes in latest version of spring boot(2.3.0).

You would need to add the below dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Note : You can use hibernate-validator instead of spring-boot-starter-validation.

Upvotes: 2

Michalis B.
Michalis B.

Reputation: 29

It depends on how you are handling your null values. If i.e. leaving a String field empty means you will send "" this will be passed as it is not a null value, hence the @NotNull annotation on your Wolf class does not apply.

Michael

Upvotes: 0

Related Questions