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

4
  • Can you add jsp form? Commented Jun 27, 2018 at 14:11
  • @GUISSOUMAIssam <%@ 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> Commented Jun 27, 2018 at 14:16
  • @GUISSOUMAIssam I added to my post it'll be more readable Commented Jun 27, 2018 at 14:22
  • @user8116296 This is from the udemy course of Chad. Were you able to fix this ? What was the solution. Commented Feb 24, 2021 at 7:42

7 Answers 7

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>
Sign up to request clarification or add additional context in comments.

5 Comments

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 ..
add the whole stack trace
It should work u seem to have the dependency already in your classpath
I cannot paste it here because it's too long for comment. It's pastebin link for error pastebin.com/hTYN6gux
Please check link I think you need to remove the <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId>
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?

1 Comment

It's project created without maven and I don't have pom.xml
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.

2 Comments

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.
I downgraded to 5.2.4 but even that didn't work.
0

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

Comments

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

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.