Reputation: 5926
I have a web controller in Spring MVC:
@RequestMapping("/")
public String create(@Valid @ModelAttribute Device device, BindingResult bindingResult) {
return getDefaultView();
}
jsp view:
<form:form role="form" commandName="device">
<form:input path="name" class="form-control"/>
<form:errors path="name" cssClass="text-danger"/>
<button type="submit">Submit</button>
</form:form>
Suppose that my Device class has only one attribute name. I want to validate it (example length >= 5)
public class DeviceDTO {
@Size(min = 5)
String name;
//getter & setter..
}
After run this, I input string "abc" in name field then submit, The form will show as:
We can see there are old value & error message. But in some cases that I want to manually validate with my own criteria (that annotation cannot handle), I remove @Size annotation and change my controller like this:
@RequestMapping("/")
public String create(@Valid @ModelAttribute Device device, BindingResult bindingResult) {
if(device.getName().length() < 6)
bindingResult.addError(new FieldError("device", "name", "custom error"));
return getDefaultView();
}
But now, when I submit form with "abc" value, my custom error is shown but my old value of name field not
But if I use directly ${device.name}, it still shows "abc" value.
Upvotes: 2
Views: 3461
Reputation: 2582
Try the code below:
@RequestMapping("/")
public String create(@Valid @ModelAttribute Device device, BindingResult bindingResult) {
if(device.getName().length() < 6)
bindingResult.addError(new FieldError("device", "name",device.getName(), false, null, null, "custom error"));
return getDefaultView();
}
Upvotes: 6