Reputation: 73
I'm writing my first spring boot app and I'm stuck with this problem. I can't show error message to user. Object without that data is not saved in the database and that is OK. But showing error message is the problem. When I debug i get errors size = 0
This is model
@Size(min = 1, message = "Address is invalid.")
@NotNull
@Column
private String address;
Controller
@RequestMapping(value = "/create", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String createNewBusiness(@Valid @ModelAttribute("business") Business business,
BindingResult result, Model model) {
model.addAttribute("userEmail", getUserEmail());
logger.info("/business/create:" + business.toString());
LocationResponse locationResponse = geoService.getCoords(business.getAddress());
if (locationResponse.getStatus().equals("OK")) {
business.setLatitude(locationResponse.getResults().get(0).getGeometry().getLocation().getLat());
business.setLongitude(locationResponse.getResults().get(0).getGeometry().getLocation().getLng());
business.setUserId(getUserId());
businessService.createNew(business);
model.addAttribute("business", business);
} else {
business.setAddress(null);
model.addAttribute("business", business);
}
if (result.hasErrors()) {
List<FieldError> errors = result.getFieldErrors();
for (FieldError error : errors ) {
System.out.println (error.getObjectName() + " - " + error.getDefaultMessage());
}
return "newBusiness";
}
return "business";
}
Thymeleaf
<div class="input-field left m-0 w-100">
<i class="fa fa-map-marker prefix grey-text" aria-hidden="true"></i>
<input placeholder="Address" id="inputAddress" name="address" type="text" class="validate my-0" th:required="true">
<label th:errors="*{address}" th:if="${#fields.hasErrors('address')}" >Invalid address</label>
</div>
Upvotes: 3
Views: 1663
Reputation: 14035
Did you define a Validator
in your @SpringBootApplication
?
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
@Bean
public Validator validator() {
return new LocalValidatorFactoryBean();
}
}
Upvotes: 1