Reputation: 7357
I have controller's method:
@RequestMapping(value="/eusers", method=RequestMethod.POST)
public @ResponseBody String createEUser(@Valid @RequestBody EUser e, BindingResult result){
if(result.hasErrors()){
return "error";
}
//EUser creation and adding to a DB
return "OK";
}
EUser.java is the following:
@Entity
@Table(name="users")
public class EUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Max(5)
@Column(name="name")
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The issue is when I even pass the pararmeter which contains less than 5 characters ("asd"
in the case) I got the validation error message:
org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'euser' on field 'name': rejected value [asd];
codes [Max.user.name,Max.name,Max.java.lang.String,Max];
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [euser.name,name];
arguments []; default message [name],5];
default message [must be less than or equal to 5]
But the asd
string is valid! What's wrong? In the error message we can see that rejected value [asd];
. Why?
Upvotes: 1
Views: 1071
Reputation: 6197
Bean validation does not specify use of @Max
for strings. From hibernate validation documentation:
Hibernate Validator allows some constraints to be applied to more data types than required by the Bean Validation specification (e.g. @Max can be applied to Strings). Relying on this feature can impact portability of your application between Bean Validation providers.
So, try use @Size
, like this, for compliance with all providers:
@Column
@Size(max=5)
private String name;
Upvotes: 4
Reputation: 18194
@Max
is for numbers. You should use @Size
to validate string length.
Upvotes: 3