3

I have a problem with Hibernate Validator. I putted in my code @Size annotation but when I am running app on Tomcat server I can submit without filled text field. What is wrong with this code?

Customer class:

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class Customer {

    private String firstName;

    @NotNull(message="is required")
    @Size(min=1, message="is required")
    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

CustomerController class:

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;

@Controller
@RequestMapping("/customer")
public class CustomerController {

    @RequestMapping("/showForm")
    public String showForm(Model theModel) {
        theModel.addAttribute("customer", new Customer());
        return "customer-form";
    }

    @RequestMapping("/processForm")
    public String processForm(
            @Valid @ModelAttribute("customer") Customer theCustomer, BindingResult theBindingResult) {

        if (theBindingResult.hasErrors()) {
            return "customer-form";
        } else {
            return "customer-confirmation";
        }
    }
}

dispatcher-servlet.xml

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <!-- Add support for scanning countries from file -->
    <util:properties id="countryOptions" location="WEB-INF/countries.properties" />

    <!-- Step 3: Add support for component scanning -->
    <context:component-scan base-package="com.rafal.springdemo" />

    <!-- Step 4: Add support for conversion, formatting and validation support -->
    <mvc:annotation-driven/>

    <!-- Step 5: Define Spring MVC view resolver -->
    <bean
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

customer-form.jsp

   <%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Customer Registration Form</title>
    <style>
        .error {color:red}
    </style>
</head>
<body>
    <form:form action="processForm" modelAttribute="customer" >

        First name: <form:input path="firstName" />

        <br><br>

        Last name (*): <form:input path="lastName" />
        <form:errors path="lastName" cssClass="error" />

        <br><br>

        <input type="submit" value="Submit" />

    </form:form>




</body>
</html>

And screenshots from lib folder and project structure.

Content of lib directory

Project structure and dependencies

7 Answers7

1

You might need to add the following bean definition in your xml.

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>

OR

for custom error messages you need to create a message.properties in the resource folder and use ResourceBundleMessageSource

<!-- bind your messages.properties -->
<bean class="org.springframework.context.support.ResourceBundleMessageSource"
    id="messageSource">
    <property name="basename" value="messages" />
</bean>
Parth Kansara
  • 189
  • 1
  • 11
  • Now I cannot run my app and i've got errors. `org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping': Invocation of init method failed; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Error loading class [org.springframework.validation.beanvalidation.LocalValidatorFactoryBean] for bean with name 'validator' defined in ServletContext resource [/WEB-INF/dispatcher-servlet.xml]: problem with class file or dependent class; nested ..` –  Jun 27 '18 at 14:56
  • add the whole stack trace – GUISSOUMA Issam Jun 27 '18 at 15:03
  • It should work u seem to have the dependency already in your classpath – Parth Kansara Jun 27 '18 at 15:03
  • I cannot paste it here because it's too long for comment. It's pastebin link for error https://pastebin.com/hTYN6gux –  Jun 27 '18 at 15:12
  • Please check [link](https://stackoverflow.com/questions/26637800/classnotfoundexception-javax-validation-validatorfactory) I think you need to remove the `javax.validation validation-api` – Parth Kansara Jun 27 '18 at 16:22
0

Did you try to place

 <!-- Hibernate Validator -->
  <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
     <version>5.4.1.Final</version>
 </dependency>

in your pom.xml?

Eunito
  • 416
  • 5
  • 22
0

I used the jar hibernate-validator-5.1.3.Final and it worked for me. I was facing the same problem when I was using 6.

Hirshi
  • 1
  • I was facing the same issue where the bean validations were not working, using hibernate validator version 6.1.5. So I downgrade to 5.1.3 and it worked for me. I am not sure why hibernate validator 6.1.5 did not work with the code above. – Hirshi Sep 18 '20 at 18:34
  • I downgraded to 5.2.4 but even that didn't work. – vibhor vaish Feb 24 '21 at 07:54
0

Restarting IntelliJ fixed this for me. Really. 25 minutes of my life I'll never get back.

andydavies
  • 3,081
  • 4
  • 29
  • 35
0

I had the same problem.

My solution was using older version of Hybernate validator. The thing is they changed package name into jakarta. instead of javax. from version 6.2 and it was causing problems for me, because spring class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" was still implementing javax.validation.ValidatorFactory

Roman_G
  • 11
  • 3
0

I had the same problem using Hibernate Validator 7. I used Hibernate 6 and the problem was solved!

0

I was having the same problem, To solve this use @NotEmpty instead of @NotNull, this should fix the issue.