简体   繁体   中英

Spring validation with hibernate validator not finding validation errors

Intended function: My website form should redirect to the form processed page if the last name has a length of greater than one. If not, it should redirect the user back to the login page. The error: When the last name field has less than 1 character, I still get redirected to the form processed page.

Customer class:

package com.example.springvalidation.model;


import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class Customer {
    private String firstName;

    @NotNull(message="This field is required")
    @Size(min=1, message="length must be greater than 1")
    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;
    }
}

Controller class:

package com.example.springvalidation.controllers;

import com.example.springvalidation.model.Customer;
import org.springframework.stereotype.Controller;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;

@Controller
public class MainController {

    @RequestMapping("/")
    public ModelAndView displayForm(ModelAndView mv) {
       mv.addObject("customer", new Customer());
       mv.setViewName("customer-form");

       return mv;
    }

    @RequestMapping("/processForm")
    public String processForm(@Valid @ModelAttribute("customer") Customer customer,
                                    BindingResult br) {
        if (br.hasErrors()) {
            return "customer-form";
        }
        return "form-processed";

    }
}

customer-form.jsp:

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<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>

form-processed.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>Customer processed</title>
    </head>
    <body>
        <h1>Customer successfully processed!</h1>
        <hr>
        <h2>Customer info:</h2>
        <p1>
            Customer first name: ${customer.firstName}
            <br><br>
            Customer last name: ${customer.lastName}
        </p1>
    </body>
</html>

My libraries:

图书馆

Add GroupSequence to validate lastName not empty and length check.

Step1: First create two interfaces as FirstValidation.class and SecondValidation.class

public interface FirstValidation
{
}

public interface SecondValidation
{
}

Step2: Then Create GroupSequence interface as follows.

@GroupSequence({ FirstValidation.class, SecondValidation.class })
public interface OrderedCheck
{
}

Step3: Don't use @NotNull for the check string is empty. Use @NotBlank . It is more appropriate. And add groups like this.

@NotBlank(groups = {FirstValidation.class} , message="This field is required")
@Size(min=1, groups = {SecondValidation.class} , message="length must be greater than 1")
private String lastName;

Step4: Finally change your controller method as follows. Note: Use @Validated instead of @Valid

@RequestMapping("/processForm")
public String processForm(@Validated({OrderedCheck.class})  @ModelAttribute("customer") Customer customer,
                                BindingResult br) {
    if (br.hasErrors()) {
        return "customer-form";
    }
    return "form-processed";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM