16

I want to validation my form, but this not work. My entity class

import java.io.Serializable;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Email;

@Entity
@Table(name = "users")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue
    @Column(name = "id")
    private Integer id;
    @NotNull
    @Size(max = 20)
    @Column(name = "username")
    private String username;
    @NotNull
    @Size(max = 20)
    @Column(name = "password")
    private String password;
    @NotNull
    @Size(max = 20)
    @Column(name = "firstName")
    private String firstName;
    @NotNull
    @Size(max = 20)
    @Column(name = "lastName")
    private String lastName;
    @Size(min = 11, max = 11)
    @Column(name = "personalId")
    private String personalId;
    @Size(max = 40)
    @Column(name = "city")
    private String city;
    @Size(max = 40)
    @Column(name = "address")
    private String address;
    @NotNull
    @Email
    @Size(max = 30)
    @Column(name = "email")
    private String email;
    @Size(min = 9, max = 9)
    @Column(name = "phone")
    private String phone;
    @OneToMany(mappedBy = "user")
    private Set<UserRole> userRoleSet;
}

adminList.jsp and form go to addAdmin page:

<form action="addAdminForm" method="post">
    <input type="submit" value="Dodaj administratora" />
</form>

addAdmin.jsp page formule:

    <form:form action="addAdmin" modelAttribute="user" method="post">
    <form:label path="username">Login: </form:label>
    <form:input path="username" />
    <form:errors path="username" cssClass="error" />
    <br />
    <form:label path="password">Hasło: </form:label>
    <form:password path="password" />
    <form:errors path="password" cssClass="error" />
    <br />
    <form:label path="firstName">Imię: </form:label>
    <form:input path="firstName" />
    <form:errors path="firstName" cssClass="error" />
    <br />
    <form:label path="lastName">Nazwisko: </form:label>
    <form:input path="lastName" />
    <form:errors path="lastName" cssClass="error" />
    <br />
    <form:label path="email">Email: </form:label>
    <form:input path="email" />
    <form:errors path="email" cssClass="error" />
    <br />
    <input type="submit" value="Dodaj" />
</form:form>

Controller:

    @RequestMapping(value = "/admin/addAdminForm", method = RequestMethod.POST)
public ModelAndView goAddAdminForm() {
    ModelAndView mav = new ModelAndView("admin/addadmin");
    mav.addObject("user", new User());
    return mav;
}

@RequestMapping(value = "/admin/addAdmin", method = RequestMethod.POST)
public String addAdmin(@Valid @ModelAttribute("user") User user,
        BindingResult result, Model model) {
    if (result.hasErrors()) {
        return "admin/addadmin";
    } else {
        userService.createUser(user);
        user = userService.findByUsername(user.getUsername());
        UserRole userRole = new UserRole("ROLE_ADMIN");
        userRole.setUser(user);
        userRoleService.createUserRole(userRole);
        return "redirect:/admin/adminlist";
    }
}

When i try send empty formule i should get error messages result.hasErrors() not return error and my application go to else and try save user. Why @Valid not work?

The Nightmare
  • 701
  • 5
  • 16
  • 36
  • Hi, I have got a similar case but in my case the @NotEmpty is also not working. can you please let me know if I need to configure other than this all above? – Toseef Zafar Aug 17 '15 at 23:03

9 Answers9

50

After upgrading my project to Spring Boot 2.3.0, I struggled for hours with the same issue until I realized that as of #19550, Web and WebFlux starters do not depend on the validation starter by default anymore. If your application is using validation features, you’ll need to manually add back a dependency on spring-boot-starter-validation in your build file.

ntholi
  • 887
  • 2
  • 13
  • 19
  • 1
    Yeah before importing starter-validation compiler was showing issues and now everything is fine for compiler but it still isn't working. Showing zero errors in `Error` object – Muhammad Muzammil May 28 '20 at 11:27
  • 1
    this should be the accepted answer, thanks for sharing – irshad.ahmad Jun 05 '20 at 20:07
  • 1
    True @irshad.ahmad, and I suspect most people in 2021 arriving at this post will find it's due to missing this dependency. Is it possible to change the accepted answer, @the-nightmare? – Kevin-Prichard Feb 10 '21 at 17:37
9

I struggled with the same issue in my Spring Boot 2.4.1 project. You'll need to add this dependency in your pom.xml file

...
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
...
j.Frederic
  • 101
  • 1
  • 2
6

Are you sure that the validations don't work? Unless you have for example StringTrimmerEditor registered, your fields will actually be String instances with length equal to 0, not null values when you submit the form and therefore the annotation would consider such values to be valid.

If you want to validate that String is not blank (not null and not an empty String), use for instance the @NotBlank annotation. Also I just tried it myself and the @Email annotation also passes for empty Strings, which would mean that your empty form IS actually valid right now.

Bohuslav Burghardt
  • 33,626
  • 7
  • 114
  • 109
  • I added `@NotBlank` and `@Valid` work. Why `@NotNull` is not sufficient? – The Nightmare Nov 24 '14 at 19:01
  • 2
    I don't see a question mark but I assume that the last part is a question :). `@NotNull` only checks if the value is not `null`, but the value you get from the form is actually `""`, meaning String instance with length 0, which is not `null`. Hope this explains it – Bohuslav Burghardt Nov 24 '14 at 19:04
6

I had the same problem in Kotlin with old beans automatically converted from Java. They were missing the field target specifier, without which the javax.validation annotations had no effect.

A Kotlin snippet from the question code (with field to solve the problem):

@field:NotNull
@field:Size(max = 20)
@Column(name = "username")
var username:  String
Paulo Merson
  • 13,270
  • 8
  • 79
  • 72
4

I had the same error (the application did not validate).

I added

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

and worked!

Greenonline
  • 1,330
  • 8
  • 23
  • 31
andrecoweb
  • 171
  • 1
  • 2
  • 6
3

I had the same issue with 2.5.0 (SNAPSHOT) spring boot project. I added the below dependency in the pom.xml file and it worked.

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Poulami Pal
  • 201
  • 3
  • 6
0
<mvc:annotation-driven/>

check whether above tag is declared within dispatcher-servlet.xml or not. This tag will be active all annotation.

Anurag
  • 1,018
  • 1
  • 14
  • 36
  • You don't need a code snippet to put a one liner code suggestion. This is misleading to the reader and they will run thinking it will produce a result but here it is just a single code which can be formatted as a code sample instead. – Anurag May 07 '16 at 13:45
0

Today (2018-04-22), the hibernate-validator have been update to version 6.0.9.Final . On my test, I found the nested object valid using @Valid can be work <= version 5.2.5.Final, I don't understand why the latest can't working (maybe someone can explain in future), here is my code:

@JsonIgnoreProperties(ignoreUnknown = true)
public class PackQueryReq {

    // ......

    @NotNull(message = "params can't be NULL")
    @Valid
    private PackQueryParams params;
}
public class PackQueryParams {

    @Min(value=1)
    @NotNull(message = "enterpriseId can't be NULL")
    private Integer enterpriseId;
}

And on spring MVC controller:

public Resp query(@RequestBody @Valid PackQueryReq packQuery) {
   //...
}
Derek J.
  • 126
  • 6
0

I had to change the version of hibernate-validator. With 8.0.0 does not work, but with 6.1.5 does.

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>6.1.5.Final</version>
    </dependency>
Spilvergo
  • 31
  • 4