Issue
I am working on spring mvc web application. In application, I put @NotBlank
annotation for validation on username
field in sign up form. I fill the username
field and click on Submit
button that time i get validation error message, but I fill username
field so why BindingResult
produce error behind username
field and my @Size
annotaion is not worked if insert less than 3 or greater than 12 character.
Here down is code:
Entity:
public class Registration {
@NotBlank(message = "Username can not be empty !")
@Size(min = 3, max = 12, message = "Username must be in 3 to 12 character") // Not working
private String username;
private String email;
private Boolean agree;
// constructor, getter, setter and toString()
}
Controller:
@GetMapping("/form")
public String formPage(Model mdl)
{
mdl.addAttribute("registration", new Registration());
return "form";
}
@PostMapping("/register")
public String registerUser(@Valid @ModelAttribute("registration") Registration registration,
BindingResult result)
{
if(result.hasErrors())
{
System.out.println(result);
return "form";
}
return "success";
}
form.html:
<form class="bg-white p-5" th:action="@{/register}" method="post" th:object="${registration}">
<h1 class="text-center pt-2 pb-2">Signup Form</h1>
<div class="mb-3">
<label for="username" class="form-label">Username</label>
<input type="text"
class="form-control"
th:value="${registration.username}"
id="username" />
<p th:each="error : ${#fields.errors('username')}" th:text="${error}">
</p>
</div>
<div class="mb-3">
<label for="email" class="form-label">Email address</label>
<input type="text"
class="form-control"
id="email"
th:value="${registration.email}"
aria-describedby="emailHelp" />
</div>
<div class="mb-3 form-check">
<input type="checkbox"
class="form-check-input"
id="exampleCheck1">
<label class="form-check-label" for="exampleCheck1">Check me out</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Xml for validation:
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
Snapshot of problem:
Solution
The problem is here
<input type="text"
class="form-control"
th:value="${registration.username}"
id="username"/>
You are missing the name
attribute.
<input type="text"
class="form-control"
th:value="${registration.username}"
id="username"
name="username"/>
This will fix it.
The form normally is bound to an object - Registration
in your case, using the name
attributes of input
tags. The annotations are working, the problem is that you are receiving null
username in Registration
due to that missing attribute.
Answered By - Chaosfire
Answer Checked By - David Marino (JavaFixing Volunteer)