Validation not working on spring boot and hibernate

18,247

Solution 1

seems jar conflicts issue as org.hibernate.validator:hibernate-validator:jar(javax.validation:validation-api:jar is part of hibernate validator) is part of spring web dependency so no need to add extra dependency which might conflict so recommend to remove below dependencies and build project again by clean install(mvn clean install).

remove below dependencies:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.0.12.Final</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

and make sure you access error message below: not required braces and property name match with your actual message property name you defined.(camelcase matters with name).

@NotEmpty(message = "officename.notempty")

Solution 2

I migrated from Spring Boot 2.2.4.RELEASE to 2.4.2 and as soon as I made the changes, the validation starts failing.

The reason to start failing is to remove the validation dependencies from web module from Spring Boot version 2.3.

I made below changes to run the validation.

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>${hibernate.validator}</version>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>${validation.api}</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.logging</groupId>
            <artifactId>jboss-logging</artifactId>
            <version>${jboss.logging.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml</groupId>
            <artifactId>classmate</artifactId>
            <version>${fasterxml.classmate.version}</version>
        </dependency>

Change the versions accordingly.

Share:
18,247
Ashwin Karki
Author by

Ashwin Karki

Updated on June 22, 2022

Comments

  • Ashwin Karki
    Ashwin Karki almost 2 years

    I am new to spring boot and hibernate.I have declared a model class Office which is :

    package com.ashwin.officeproject.model;
    import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
    import org.springframework.data.annotation.CreatedDate;
    import org.springframework.data.annotation.LastModifiedDate;
    import org.springframework.data.jpa.domain.support.AuditingEntityListener;
    import javax.persistence.*;
    import javax.validation.constraints.NotBlank;
    import javax.validation.constraints.NotEmpty;
    import javax.validation.constraints.NotNull;
    import javax.validation.constraints.Size;
    
    import java.util.Date;
    
    @Entity
    @Table(name = "office")
    public class Office {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long officeId;
    
        @NotEmpty(message = "{officename.notempty}")
        private String officeName;
    
        @NotNull
        private int officeNumber;
    
        /*@Size(min = 8, max = 72, message = "Your offc address between 8 and 72 characters long")*/
        /*@NotEmpty(message = "Please provide a offc name")*/
        private String officeAddress;
    
        public Office() {
    
        }
    
        //ommitted getters and setters
    }
    

    I have declared my first main starting class as:

    package com.ashwin.officeproject;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
    import org.springframework.context.MessageSource;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.support.ReloadableResourceBundleMessageSource;
    import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
    
    @SpringBootApplication
    public class OfficeProjectApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(OfficeProjectApplication.class, args);
        }
    
        @Bean
        public MessageSource messageSource() {
            ReloadableResourceBundleMessageSource messageSource
              = new ReloadableResourceBundleMessageSource();
    
            messageSource.setBasename("classpath:messages");
            messageSource.setDefaultEncoding("UTF-8");
            return messageSource;
        }
    
        @Bean
        public LocalValidatorFactoryBean getValidator() {
            LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
            bean.setValidationMessageSource(messageSource());
            return bean;
        }
    
    }
    

    My controller class is:

    package com.ashwin.officeproject.controller;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.validation.Valid;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.ui.ModelMap;
    import org.springframework.validation.BindingResult;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    
    import com.ashwin.officeproject.model.Office;
    import com.ashwin.officeproject.repository.OfficeRepsitory;
    
    @Controller
    public class MainController {
    
        @Autowired
        OfficeRepsitory officeRepository;
    
    
        @RequestMapping(value = { "/office"}, method = RequestMethod.GET)
        public String office(Model model) {
           model.addAttribute("offices", new Office()); 
          return "office";
        }
    
        @RequestMapping(value = "/addOffice", method = RequestMethod.POST)
        public String submit(@Valid @ModelAttribute("offices") Office office, 
          BindingResult result, ModelMap model) {
            if (result.hasErrors()) {
                return "error";
            }
            officeRepository.save(office);
            model.addAttribute("offices", new Office()); 
            return "office";
        }
    
    }
    

    I have a office.jsp page which is:

    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
    <jsp:include page="./header.jsp" />
     <style>
          .error {
             color: #ff0000;
          }
    
          .errorblock {
             color: #000;
             background-color: #ffEEEE;
             border: 3px solid #ff0000;
             padding: 8px;
             margin: 16px;
          }
       </style>
        <form:form method="POST"  action="/addOffice"   modelAttribute="offices"  >
    
                 <table>
                    <tr>
                        <td><form:label path="officeName">Name</form:label></td>
                        <td><form:input path="officeName"/></td>
                        <form:errors path = "officeName" cssClass = "error" />
    
                    </tr>
                    <tr>
                        <td><form:label path="officeNumber">Number</form:label></td>
                        <td><form:input path="officeNumber"/></td>
    
    
                    </tr>
                    <tr>
                        <td><form:label path="officeAddress">
                          Address</form:label></td>
                        <td><form:input path="officeAddress"/></td>
    
    
                    </tr>
                    <tr>
                        <td><input type="submit" value="Submit"/></td>
                    </tr>
                </table>
            </form:form>
    
    
    <jsp:include page="./footer.jsp" />    
    

    My pom.xml is:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.3.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.ashwin</groupId>
        <artifactId>OfficeProject</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>OfficeProject</name>
        <description>OfficeProject</description>
    
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>6.0.12.Final</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <scope>runtime</scope>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
    
            <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
    </dependency>
    
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
    </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    

    When I click the submit button then if the input field in my form are empty,I wanted to validate my form and show the message below the input field like "Please provide valid office name" .But what is happening is that when i hit the submit button then it is going to my error.jsp page but it is not showing any validation message which i have declared above.My error page displaying is:

    error.jsp

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>
    <p>Error</p>
    </body>
    </html>      
    

    I am not getting any error in my console in eclipse too.It is just redirecting me in error.jsp page when my form's field is empty.

  • Ashwin Karki
    Ashwin Karki about 5 years
    i need to delete both or require one of them?
  • kj007
    kj007 about 5 years
    Need to delete both as they are part of web dependency
  • Ashwin Karki
    Ashwin Karki about 5 years
    no bro if u have teamviewer can u come and look at my code?
  • Ashwin Karki
    Ashwin Karki about 5 years
    sorry i didnt understand what is this zoom link?
  • Ashwin Karki
    Ashwin Karki about 5 years
    do i need to signup ? i managed to bring the error message but it is coming in {officename.notempty} like this
  • kj007
    kj007 about 5 years
    is there any issue you seeing in directly joining??
  • Ashwin Karki
    Ashwin Karki about 5 years
    its is teeling me to sing in . Should i need to create a account or what? dont u have team viewer?
  • kj007
    kj007 about 5 years
    you can enter any personal email there to join if required as dont use teamviewer..
  • donny
    donny about 4 years
    i'm facing same issue, but i'm still error even i followed your instruction, please check it out github.com/black-lotus/ppm-tool-be on ValidDateValidator
  • MartinBG
    MartinBG almost 4 years
    Starting from version 2.3.0.RELEASE Spring Boot Web and WebFlux starters no longer depend on the validation starter, so you have to add spring-boot-starter-validation to your pom.xml. For details check 2.3.0 Release notes
  • Janaka Bandara
    Janaka Bandara over 2 years
    Just a tip, you can check if HV is properly initialized in the first place by checking for the following log line at app startup (this is from a Spring Boot app, but other platforms should also probably display it): [background-preinit] INFO Version HV000001: Hibernate Validator 5.3.5.Final