spring mvc javax.validation.UnexpectedTypeException: No validator could be found for type: java.lang.String

911 views Asked by At

I try to use the validators for the first time with Spring MVC and I always get the exception:

javax.validation.UnexpectedTypeException: No validator could be found for type: java.lang.String
    at org.hibernate.validator.engine.ConstraintTree.verifyResolveWasUnique(ConstraintTree.java:236)
    at org.hibernate.validator.engine.ConstraintTree.findMatchingValidatorClass(ConstraintTree.java:219)
    at org.hibernate.validator.engine.ConstraintTree.getInitializedValidator(ConstraintTree.java:167)
    at org.hibernate.validator.engine.ConstraintTree.validateConstraints(ConstraintTree.java:113)
    at org.hibernate.validator.metadata.MetaConstraint.validateConstraint(MetaConstraint.java:121)
    at org.hibernate.validator.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:334)

Here is my annoted class for validation:

public class AbstractEmployeDto implements Employable, Comparable<AbstractEmployeDto> {

private Set<AbstractClientDto> listeClients = new TreeSet<AbstractClientDto>();

private Long id;

@NotEmpty
private String nom;

@NotEmpty
private String prenom;

@DateTimeFormat(pattern="dd/MM/yyyy")
@Past
private String dateNaissance;

@Size(min=10)
private String telephone;

@Email
private String email;

private TypeEmploye typePersonne;

private String rue;

@Size(min=4, max=4)
private String npa;

getter and setter ...

And the controller with the annotation @valid:

@RequestMapping(value = "/saveNew", method = RequestMethod.POST)  
    public ModelAndView saveNewEmploye(@ModelAttribute("command") @Valid AbstractEmployeDto employe,   
       BindingResult result) { 
        Map<String, Object> model = new HashMap<String, Object>();
        if(result.hasErrors()){
            return new ModelAndView("/employes/add.html", model);  
        }
...
1

There are 1 answers

0
Ali Dehghani On BEST ANSWER

@Past and @DateTimeFormat must be used on Date or Calendar not a String. As bean validation doc says:

The annotated element must be a date in the past. Now is defined as the current time according to the virtual machine. The calendar used if the compared type is of type Calendar is the calendar based on the current timezone and the current locale.

Supported types are:
java.util.Date
java.util.Calendar
null elements are considered valid.

Porbably you need to use somehting like this:

@DateTimeFormat(pattern="dd/MM/yyyy")
@Past
private Date dateNaissance