javaspringvalidationspring-mvcjavax-validation

Old Spring and email validation


For a middleware that has Java 1.8_431 there is a Spring application

<springframework.version>4.3.1.RELEASE</springframework.version>

I have a model that has an email field that I must to validate and it is represented by this code:

import javax.validation.constraints.Email;

/**
 * The Class RegForm.
 */
public class RegForm {
....


    /** The email. */
    @Email(message = "Insert a valid email")
    private String email;

//getter and settser
}

The POM of this application is composed:

<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.1.1.Final</version>
</dependency>

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.0.1.Final</version> <!-- Versione 2.0 o superiore -->
</dependency>

<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.el</artifactId>
    <version>3.0.0</version> <!-- Necessario per l'Expression Language -->
</dependency>

The Spring Controller that I use this model is:

//many imports
import javax.validation.Valid;
....

@Controller
@RequestMapping("/reg")
public class RegController {
    
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(@ModelAttribute("regForm") @Valid @RequestBody RegForm  regForm,
            BindingResult result, Model model, final RedirectAttributes redirectAttributes, HttpServletRequest req)
            throws AcceleratoreException {
......
}

When I start the application and I call this API, the server response status 500 and the log says:

Root cause of ServletException.
javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'javax.validation.constraints.Email' validating type 'java.lang.String'. Check configuration for 'email


Solution

  • I think you're using a pretty old version of hibernate validator.

    Do you need to use org.hibernate.validator.constraints.Email (this is deprecated in later releases for jakarta.validation.constraints.Email)