Home > Blockchain >  Why validation is not worked
Why validation is not worked

Time:04-15

I am working on Spring MVC project. I use thymeleaf as view. While click on Register button my name field is null but not get validation error for @NotBlank name field.

Here down is my code:

Entity

public class User {
    ...
    ...

    @NotBlank(message = "Please enter the your name !!")
    private String name;

    // getter setter
}

Controller

@RequestMapping(value = "/user", method = RequestMethod.POST)
    public String saveUser(@Valid @ModelAttribute(name = "userentity") User user, 
                 BindingResult bindingResult, Model mdl)
    {
        if(bindingResult.hasErrors())
        {
            System.out.println(bindingResult);
            mdl.addAttribute("userentity", user);
            return "signup";
        }
        smartService.saveUser(user);
        return "signup";
    }

Thymeleaf

<form th:action="@{/user}" method="post" th:object="${userentity}">
    
    <div >
        <label  for="name">Name</label>
        <input type="text" 
        id="name"
        
        name="name" />
        <div  th:each="e: ${#fields.errors('name')}" th:text=${e}>
          
        </div>
    </div>

    <div >
      <button type="submit" >Register</button>
  </div>

</form>

Dependencies uses for validation

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
</dependency>
        
<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
</dependency>

CodePudding user response:

Your validation annotations only work if either the controller or your the method in your controller is annotated with

@Validated

so you should either have

@Validated
@RequestMapping(value = "/user", method = RequestMethod.POST)
public String saveUser(@Valid @ModelAttribute(name = "userentity") User user, BindingResult bindingResult, Model mdl) {

or

@RestController
@Validated
@RequiredArgsConstructor
public class YourControllerName {

private final SmartService smartService;

@RequestMapping(value = "/user", method = RequestMethod.POST)
public String saveUser(@Valid @ModelAttribute(name = "userentity") User user, BindingResult bindingResult, Model mdl) {

for your example that should be working. Be careful however with child objects and Lists. These additional need the @Valid annotation. I would suggest reading up on validation annotations here https://www.baeldung.com/spring-valid-vs-validated

CodePudding user response:

In your thymeleaf you should add this line required autofocus="autofocus" in your name input tag. Like -

<input id="firstName"  th:field="*{name}"
                           required autofocus="autofocus" />

this should work. It is running fine in my project.

  • Related