Reputation: 1205
Qustion:
I am looking for a good solution to validate my data in Spring MVC
controller and populate the errors with Knockout JS
. I imagine something similiar to the existing <form:errors path="">
from Spring Tags.
The solution should provide following properties:
@ModelAttribute
and @Valid
Does something similar already exist? I am also open to switch to another JS Framework if this would provide the needed functionalities. (Angular, Backbone etc.)
My custom solution:
I store all errors in a Map<String, String>
where the key is the field name and the value is the error message and populated the errors in Knockout. The problem with this solution is, that KnockoutJS looses all unbinded fields after validation.
Validate:
helper.getErrors().put("firstName", messageSourceProvider.getMessage("validation.requiredDefault"));
Serialize:
JSONSerializer serializer = new JSONSerializer();
serializer.include("helper");
serializer.include("helper.errors");
String json = serializer.serialize(helper);
Knockout:
<!-- ko foreach: errors -->
<!-- ko if: key === 'firstName' -->
<span data-bind='text: value' class="spring-error ordinary-tooltip fa fa-lg fa-exclamation-circle"></span>
<!-- /ko -->
<!-- /ko -->
Upvotes: 5
Views: 580
Reputation: 528
The method I've undertaken to handle your problem is to fire off an ajax call prior to allowing the form to submit. If there are validation issues or errors I stop the form from submitting and display the errors. This way the bindings are still intact and after the user fixes the issues the form data can be resubmitted again.
Upvotes: 0