Home > Software engineering >  Validator Framework @Min, @Max, @NotBlank not working
Validator Framework @Min, @Max, @NotBlank not working

Time:06-03

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

CodePudding user response:

define in your pom.xml the validation dependency:

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

CodePudding user response:

To work this you have to define Validator bean in your configuration.

@Bean
public LocalValidatorFactoryBean validator() {
    LOGGER.info("Instatntiating Bean for Message Source ");
    LocalValidatorFactoryBean validatorFactoryBean = new LocalValidatorFactoryBean();
    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
    messageSource.setBasename("classpath:"   PROPERTY_PREFIX);
    validatorFactoryBean.setValidationMessageSource(messageSource);
    LOGGER.info("Instatntiating Bean for Message Source completed");
    return validatorFactoryBean;
}
  • Related