Rivak Shah
Rivak Shah

Reputation: 29

Spring Boot @Valid Not Giving Error Message or Has Error is Always set to False

CONTROLLER CLASS CODE.

@GetMapping("/admin/home")
public String adhomePage(@ModelAttribute("schoolModel") SchoolModel school, Model model) {
    return "admin/home";
}

@PostMapping("/admin/saveschool")
public String saveSchool(@Valid @ModelAttribute("schoolModel") SchoolModel schoolModel, BindingResult result) {
    System.out.println(schoolModel.toString()+">>>>>>>>>>>>>>>>>>>>");
    System.out.println(result.hasErrors()+"RESULT HASE ERROR");
    System.out.println(result.getAllErrors().toString());
    if (result.hasErrors()) {
        System.out.println("ERROR");
        System.out.println(result.getAllErrors().toString());
    }
    return "admin/home";
}

MODEL CLASS CODE

package com.gatepass.web.model;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;

import org.springframework.lang.NonNull;


public class SchoolModel {
    
    @NotEmpty(message = "User's name cannot be empty.")
    @NotBlank()
    @NonNull()
    @Size(min=2, max=3)
    private Long id;
    
    @NotEmpty(message = "User's name cannot be empty.")
    @Size(min=2, max=2)
    private String name;
    
    @NotEmpty(message = "User's name cannot be empty.")
    @Size(min=2, max=2)
    private String email;
    
    @NotEmpty(message = "User's name cannot be empty.")
    @Size(min=2, max=30)
    private String mobileNumber;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getMobileNumber() {
        return mobileNumber;
    }

    public void setMobileNumber(String mobileNumber) {
        this.mobileNumber = mobileNumber;
    }

    @Override
    public String toString() {
        return "SchoolModel [id=" + id + ", name=" + name + ", email=" + email + ", mobileNumber=" + mobileNumber + "]";
    }
    
}

HTML CODE

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
 <link th:href="@{/css/style.css}" rel="stylesheet" />
<title>Insert title here</title>
</head>
<body>
    <h1>HOME PAGE VIEW FOR ADMIN</h1>
    <form th:action="@{/logout}" method="post">
        <input type="submit" value="logout">
        <input 
          type="hidden" 
          th:name="${_csrf.parameterName}" 
          th:value="${_csrf.token}" />
    </form>
      
      <br></br>
    <form th:action="@{/admin/saveschool}" th:object="${schoolModel}" method="post">
        <input type="text" th:field="*{id}">
        <input type="text" th:field="*{name}">
        <input type="text" th:field="*{email}">
        <input type="text" th:field="*{mobileNumber}">
        <br></br>
        <input type="submit" value="submit"/>
    </form>
    
</body>
</html>

I am inserting a null value but the validation does not working I don't understand what is the issue I tried @validate also but it not working.

In this image if you see I am not inserting any value and submitting the form But If you see in the console it giving false but it must be true I am new to spring boot please help me out with this problem.

I am trying to add validation rules in the spring boot application I have created a form that contains the school object and this school object is mapped with modelAttribute.

so when I am submitting the post request it should validate the rules which I added in SchoolModel class but it's not working school model have the data but it not validate the data and the binding result have a false result in hase error

Controller class

new updated code after comments.......... XML FILE

    <?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 https://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.5.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.gatepass.web</groupId>
    <artifactId>gatepass</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>GatePassSystem</name>
    <description>A project where student will register and they will get their gate pass for outside visiting</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
      <dependencies>
      
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    
       <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <scope>runtime</scope>
        </dependency>

        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-devtools</artifactId>
          <scope>runtime</scope>
          <optional>true</optional>
        </dependency>
        
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-test</artifactId>
          <scope>test</scope>
        </dependency>
            
        <dependency>
          <groupId>org.springframework.security</groupId>
          <artifactId>spring-security-test</artifactId>
          <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
        </dependency>
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-validation</artifactId>
       </dependency>        
      </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Model CLASS

    package com.gatepass.web.model;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;



@Valid
public class SchoolModel {
    
    
    private Long id;
    
    @Valid
    @NotEmpty(message = "User's name cannot be empty.")
    @Size(min=2, max=2)
    private String name;
    
    @Valid
    @NotEmpty(message = "User's name cannot be empty.")
    @Size(min=2, max=2)
    private String email;
    
    @Valid
    @NotEmpty(message = "User's name cannot be empty.")
    @Size(min=2, max=30)
    private String mobileNumber;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getMobileNumber() {
        return mobileNumber;
    }

    public void setMobileNumber(String mobileNumber) {
        this.mobileNumber = mobileNumber;
    }

    @Override
    public String toString() {
        return "SchoolModel [id=" + id + ", name=" + name + ", email=" + email + ", mobileNumber=" + mobileNumber + "]";
    }
    
}

CONTROLLER CLASS

    package com.gatepass.web.controller;


import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import com.gatepass.web.model.SchoolModel;
import com.gatepass.web.repo.RoleJpa;

@Validated
@Controller
public class WelcomeController {
    
    @Autowired
    RoleJpa roleJpa;
    
    @GetMapping("/user/home")
    public String ushomePage() {
        System.out.println(SecurityContextHolder.getContext().getAuthentication().toString()+"---USER HOME");
        //Optional<Role> r = roleJpa.findById(1L);
        return "user/home";
    }

    
    @GetMapping("/admin/home")
    public String adhomePage(@ModelAttribute("schoolModel") SchoolModel school, Model model) {
        return "admin/home";
    }
    
    @PostMapping("/admin/saveschool")
    public String saveSchool(@Valid @ModelAttribute("schoolModel") SchoolModel schoolModel, BindingResult result) {
        System.out.println(schoolModel.toString()+">>>>>>>>>>>>>>>>>>>>");
        System.out.println(result.hasErrors()+"RESULT HASE ERROR");
        System.out.println(result.getAllErrors().toString());
        if (result.hasErrors()) {
            System.out.println("ERROR");
            System.out.println(result.getAllErrors().toString());
        }
        return "admin/home";
    }
    
    @GetMapping("/manager/home")
    public String mghomePage() {
        System.out.println(SecurityContextHolder.getContext().getAuthentication().toString()+"---MANAGER HOME");
        return "manager/home";
    }

}

Upvotes: 0

Views: 1827

Answers (2)

cc9
cc9

Reputation: 9

@NotEmpty and @NotBlank() can only work on properties of string type. @Size is same. so..

@NonNull(message = "User's name cannot be empty.")
@Min(2)
@Max(3)
private Long id;

Spring example:https://spring.io/guides/gs/validating-form-input/

Upvotes: 1

Lakshman
Lakshman

Reputation: 479

I Just tried with a small demo project and it's working fine for me.

Controller.

import javax.validation.Valid;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.demo.test.dto.DemoDto;

@RestController
@Validated
public class DemoController {

    @PostMapping("/demo")
    String getValidationResponse(@Valid @RequestBody DemoDto demoDto) {
        return "all Valid";
    }

}

Model class

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

    @Valid
    public class DemoDto {
    
        @Valid
        @NotNull
        private String name;
    
        @Valid
        @NotNull
        private int age;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
    }

POM.xml

<?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 https://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.5.2</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.demo.test</groupId>
    <artifactId>demovalidator</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demovalidator</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

postman request-response. enter image description here

Valid request enter image description here

Upvotes: 1

Related Questions