Search code examples
javaspringspring-boothibernate-validator

Validator Framework @Min, @Max, @NotBlank not working


I am trying my hand in Validator ANnotations and I dont seem to have the hang of it yet

THese are my DTO

public class CustomerDTO {
    @NotBlank(message = "Blank")
    @Size(min = 3, max = 10, message = "error")
    @Pattern(regexp = "^[a-zA-Z0-9_]+", message = "Includes charectors not included")
    public String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
public class UserDTO {
    @NotBlank(message = "Blank")
    @Min(value = 3, message = "minimum len")
    @Max(value = 10, message = "max len")
    @Pattern(regexp = "^[a-zA-Z0-9_]+", message = "Includes charectors not included")
    public String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

THis is my controller

@RestController
@RequestMapping(path = "/trial")
public class UserNameStringController {

    @PostMapping(path = "/nameChange")
    public void update(@Valid @RequestBody CustomerDTO customerDTO){
        System.out.println(customerDTO.getName());
        UserDTO userDTO = new UserDTO();
        userDTO.setName(customerDTO.getName());
        System.out.println(userDTO.getName());
    }
}

This is my request body

{
   "name": "hi"
}

I am able to get a valid answer for this, it doesnt raise an error or send my error messages. I dont understand why??? Someone help please


Solution

  • define in your pom.xml the validation dependency:

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