Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annotations from javax.validation.constraints not working

What configuration is needed to use annotations from javax.validation.constraints like @Size, @NotNull, etc.? Here's my code:

import javax.validation.constraints.NotNull; import javax.validation.constraints.Size;  public class Person {       @NotNull       private String id;        @Size(max = 3)       private String name;        private int age;        public Person(String id, String name, int age) {         this.id = id;         this.name = name;         this.age = age;       } } 

When I try to use it in another class, validation doesn't work (i.e. the object is created without error):

Person P = new Person(null, "Richard3", 8229)); 

Why doesn't this apply constraints for id and name? What else do I need to do?

like image 967
Darshan Patil Avatar asked Jan 06 '12 10:01

Darshan Patil


People also ask

What does javax validation constraints NotNull do?

@NotNull validates that the annotated property value is not null. @AssertTrue validates that the annotated property value is true.

What is javax validation constraints?

Package javax. validation. constraints Description. Contains all the Bean Validation provided constraints also called built-in constraints. These constraints do not cover all functional use cases but do represent all the fundamental blocks to express low level constraints on basic JDK types.

How does javax validation valid work?

validation will validate the nested object for constraints with the help of javax. validation implementation provider, for example, hibernate validator. @Valid also works for collection-typed fields. In the case of collection-typed fields, each collection element will be validated.

What is the use of @validated annotation?

The @Valid annotation ensures the validation of the whole object.


1 Answers

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....     } } 
like image 74
atrain Avatar answered Oct 06 '22 04:10

atrain