admin管理员组

文章数量:1241095

Spring Boot Form Validation Messages Not Displaying, Saving Data Despite Errors

And for the problem details:

I am working on a Spring Boot application with form validation using @Valid and BindingResult. My form includes a name field with the following constraints:

@NotBlank(message = "Name field should be required")

@Size(min = 2, max = 20, message = "Min 2 characters and max 20 characters allowed")

private String name;

However, when I submit the form without entering a name, the validation messages are not displayed. Instead, the application proceeds with saving the data and throws the following error (see also on the image):

Something went wrong! could not execute statement [Duplicate entry '' for key 'user.UKob8kqyqqgmefl0aco34akdtpe']

Here is my controller method:

@RequestMapping(value = "/do_register", method = RequestMethod.POST)
    public String registerUser( @ModelAttribute("user")@Valid User user,BindingResult result,
            @RequestParam(value = "agreement" ,
            defaultValue = "false")boolean agreement, 
            Model model,HttpSession session)
    {
        
        try {
            
            if(result.hasErrors()) {
                System.out.println("Error "+result.toString());
                model.addAttribute("user",user);
                return "signup";
            }
            
            if(!agreement) {
                System.out.println("You didn't accept the agreement");
                throw new Exception("You didn't accept the agreement");
            }
            
            
            
            
            user.setRole("Role_User");
            user.setEnabled(true);
            user.setImageUrl("default.png");
            
            System.out.println(agreement);
            System.out.println(user);
            
            User userResult = this.userRepository.save(user);
            

//          return blank user
            model.addAttribute("user",new User());
            session.setAttribute("message", new Message("User successfully registered ! ","alert-success"));
            return "signup";
            
//          handling error here
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            model.addAttribute("user",user);
            session.setAttribute("message", new Message("Something went wrong! "+e.getMessage(),"alert-danger"));
            return "signup";
            
        }
        
    }

What I’ve Tried:

  • Checked if BindingResult captures errors (it does).

  • Ensured the form field has th:field="*{name}" in the Thymeleaf template.

  • Used th:errors="*{name}" to display errors.

  • Verified the @Valid annotation is correctly used.

Front-End Code

<!--Name Input Field  -->
                            <div class="mb-3">
                                <label for="name_field" class="form-label">Your Name</label> <input
                                    name="name" required type="text" class="form-control"
                                    th:classappend="${#fields.hasErrors('name')} ? 'is-invalid' : ''"
                                    id="name_field" th:value="${user.name}"
                                    placeholder="Enter your name here" />

                                <!-- Display validation message -->
                                <div class="invalid-feedback"
                                    th:if="${#fields.hasErrors('name')}" th:errors="*{name}">
                                    Name error</div>

                            </div>
                            <!--Name Input Field  End Here-->

I tried adding validation annotations in my User entity and used @Valid with BindingResult in my controller. I expected that when submitting the form with an empty or invalid name, the validation messages would be displayed, and the form would not be submitted. However, instead of showing the error messages, the form proceeds with submission, and I get an SQL exception due to a duplicate entry for an empty name field.

package com.ninja.entity;

import java.util.ArrayList;
import java.util.List;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;

import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;



@Entity
@Table(name = "User")
public class User {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    

    @NotBlank(message = "Name field should be required")
    @Size(min = 2, max = 20, message = "min 2 characters and max 20 characters allowed")
    private String name;
    
    @Column(unique = true)
    
    private String email;

    
    private String password;
    
    
    private String role;
    private Boolean enabled;
    private String imageUrl;
    @Column(length = 500)
    private String about;
    
    @OneToMany(cascade = CascadeType.ALL,fetch = FetchType.LAZY,mappedBy = "user") //cascade: if user deleted then all related contact related to user will be delete
    private List<Contact>contacts = new ArrayList<>();
    
    

本文标签: javaSpring Boot Form Validation Not Displaying Error Messages ProperlyStack Overflow