Home > Enterprise >  BindingResult object has not errors
BindingResult object has not errors

Time:05-29

I've the following code

Object

package com.example.demo;
import javax.validation.constraints.*;

public class Customer {

    @NotEmpty(message="first name should contain a value")
    private String firstName;
    
    public String getFirstName() {
        return firstName;
    }

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

    
}

Controller

package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.validation.BindingResult;
import javax.validation.Valid;

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

    private static int counter = 0;

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

    @RequestMapping("/processForm")
    public String processForm(@Valid @ModelAttribute("customer") Customer customer, BindingResult bindingResult) {
        return "customer-form";
    }

}

Form in a jsp file

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
    <html>

    <head></head>

    <body>
        <form:form method="POST" action="processForm" modelAttribute="customer">
            <form:label path="firstName">Name</form:label>
            <form:input path="firstName" />
            <form:errors path="firstName"/>
            <button type="submit">Submit</button>
        </form:form>
    </body>

    </html>

I've done some debugging and when I click the submit button the method processForm is called correctly, but the bindingResult has no errors. The firstName variable is empty. Why validation is not working?

CodePudding user response:

Make sure that you've declared Hibernate Validator dependency in the pom.xml (if you use maven)

<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>7.0.4.Final</version>
</dependency>

Validation constraints can be in your classpath from other libs, but validation processor being in dependency above

  • Related