Reputation: 5952
I want to validate my form fields. I followed this tutorial . I just want to show a my given error message(No need to use MessageResource,but hard coded message inside the pojo). I use Hibernate and spring validation as above tutorial used. This is my pojo which is used as the model attribute with validation annotations.
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
public class User {
@NotNull(message="username cannot be empty")
private String username;
@NotEmpty @Email(message="e mail cannot be empty")
private String email;
(... encapsulated getters and setter..)
This is my JSP.
<form:form action="register" method="post" commandName="userForm">
<table border="0">
<tr>
<td colspan="2" align="center"><h2>Spring MVC Form Demo - Registration</h2></td>
</tr>
<tr>
<td>User Name:</td>
<td><form:input path="username" />
<form:errors path="username"></form:errors>
</td>
</tr>
<tr>
<td>E-mail:</td>
<td><form:input path="email" />
<form:errors path="email"></form:errors>
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Register" /></td>
</tr>
</table>
</form:form>
Here is my controller:
@RequestMapping(method = RequestMethod.POST)
public String processRegistration( @ModelAttribute("userForm") @Valid User user
,BindingResult result
,Map<String, Object> model) {
if(result.hasErrors()){
return "registration";
}
return "profile";
inside my pom.xml,
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.1.Final</version>
</dependency>
When there is a field error, the page shows only the default error which is may not be empty
. How can I set my given error message instead of default error? Anyone can see any wrong in my implementation ?
Upvotes: 1
Views: 1885
Reputation: 569
As per your current code you'll get username cannot be empty
only if username is null. Change it to @NotEmpty
. And you'll get e mail cannot be empty
only if the email formatting is incorrect. If email is empty, the default message will be printed because you haven't attached any message to @NotEmpty
of email property. @Sanjay's suggestion will fix this.
Upvotes: 1
Reputation: 8955
Could you try this and see whether it works:
@NotEmpty(message="username cannot be empty")
private String username;
@NotEmpty(message="email cannot be empty")
@Email(message="email not well formed")
private String email;
Upvotes: 1