@Valid Annotation Is Not Working as Expected

@valid annotation is not working as expected

Your @Valid annotation is applied to the List and not the actual objects present on the list.

The annotation you have in your example validates the list and not each object of the list.

Try this

public Student addStudent(@PathVariable Integer classId,@RequestBody List<@Valid Student> students)

You can specify additional parameters as well for example you may need to validate each object on the list AND to make sure that the list is not empty, or has a minimum size etc. Those validations must be performed on the list.

How to test if @Valid annotation is working?

This solution works with Spring 5. It should work with Spring 4 as well. (I've tested it on Spring 5 and SpringBoot 2.0.0).

There are three things that have to be there:

  1. in the test class, provide a bean for method validation (PostServiceTest in your example)

Like this:

@TestConfiguration
static class TestContextConfiguration {
@Bean
public MethodValidationPostProcessor bean() {
return new MethodValidationPostProcessor();
}
}

  1. in the class that has @Valid annotations on method, you also need to annotate it with @Validated (org.springframework.validation.annotation.Validated) on the class level!

Like this:

@Validated
class PostService {
public Post save(@Valid Post post) {
return postRepository.save(post);
}
}

  1. You have to have a Bean Validation 1.1 provider (such as Hibernate Validator 5.x) in the classpath. The actual provider will be autodetected by Spring and automatically adapted.

More details in MethodValidationPostProcessor documentation

Hope that helps

Annotations from javax.validation.constraints not working

For JSR-303 bean validation to work in Spring, you need several things:

  1. MVC namespace configuration for annotations: <mvc:annotation-driven />
  2. The JSR-303 spec JAR: validation-api-1.0.0.GA.jar (looks like you already have that)
  3. An implementation of the spec, such as Hibernate Validation, which appears to be the most commonly used example: hibernate-validator-4.1.0.Final.jar
  4. In the bean to be validated, validation annotations, either from the spec JAR or from the implementation JAR (which you have already done)
  5. In the handler you want to validate, annotate the object you want to validate with @Valid, and then include a BindingResult in the method signature to capture errors.

Example:

@RequestMapping("handler.do")
public String myHandler(@Valid @ModelAttribute("form") SomeFormBean myForm, BindingResult result, Model model) {
if(result.hasErrors()) {
...your error handling...
} else {
...your non-error handling....
}
}


Related Topics



Leave a reply



Submit