3

I have Spring boot application and 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 my 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";

}

And 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>
8
  • Does my solution work for you? Please let me know about it (later). Commented Mar 26, 2018 at 13:59
  • I edited controller, but still, error message doesn't show Commented Mar 27, 2018 at 8:01
  • You´re validating buisness but you want the adress to be valid and enter it on UI. Is this field part of the buisness-Entity? Commented Mar 27, 2018 at 8:10
  • Yes, field address is part of buisness. Commented Mar 27, 2018 at 11:27
  • Try to use the field ID on UI for showing up the message. So you shopuld use inputAddress instead of adress on .hasErrors(). Last think I would expect is that you need to use the field-id... Commented Mar 27, 2018 at 11:38

3 Answers 3

2

You need to use @Valid and on some also @ModelAttribute for the parameter of createNewBusiness() - depending on your parameters and stuff.

Also you need to add th:field="*{adress}" to your inputfield because it´s the ID of this inputfield in the framework.


So in you case the method header will look like this:

public String createNewBusiness(@ModelAttribute Business business,
    @Valid Model model, BindingResult result) {
    // ...
}
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to throw a custom validation error (for example, if you're validating a field by something other than the annotation validators in your model), you can do that through BindingResult#rejectValue() method. For example:

if (business.getEmail()  == null || business.getEmail().length() == 0) {
    result.rejectValue("email", "email.missing", "Must enter email");
}

Obviously email field is just an example, as you would need that email field on your thymeleaf resource as well as the error field.

More on this topic at https://docs.spring.io/autorepo/docs/spring-framework/3.2.8.RELEASE/javadoc-api/org/springframework/validation/Errors.html#rejectValue(java.lang.String,%20java.lang.String,%20java.lang.Object[],%20java.lang.String)

Comments

0

I am a beginner in Spring Boot, so this was a small project for learning. And I am facing this issue, so what I did, I passed all the error has a list to the html as errorlist then used the each function to get the specific error for each element:

@PostMapping("/")
public String save(Model model, @Validated ProductEntity product, BindingResult result) {
    if (result.hasErrors()) {
        model.addAttribute("product", product);
        model.addAttribute("errorlist",result.getAllErrors());
        return "index";
    }

    productRepo.save(product);
    model.addAttribute("msg", "Added Product");
    model.addAttribute("product", new ProductEntity()); 
    return "index";
}

And the html to show the error was:

<div th:each="error : ${errorlist}" th:if="${error.objectName == 'productEntity' && error.field == 'price'}" th:text="${error.defaultMessage}"></div>

I was not able to find the message for invalid data using this:

<p th:if="${#fields.hasErrors('price')}" th:errors="*{price}"></p>

I hope this will help.

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.