Reputation: 972
In my case, when server-side @Valid
fails, the response contains error messages for each target input. So I don't have to write client-side validations. But I want to minimize requests beforehand using client-side validation. But me being lazy, I find myself coding basically the same validation twice.
Is there a way to generate client-side validations using server-side validations?
Upvotes: 3
Views: 222
Reputation: 2109
If you are using annotation on server side for validation, you can generate client side validation based on them.
example :
public class MyObject{
@Size(min=2, max=30, message ="Invalid size")
private String name;
//getters & setters
}
If you are using jQuery validation plugin you can add the target validation on each field. See reference for more details: https://jqueryvalidation.org/reference/
You can take all the fields and see its annotations:
Field[] fields = MyObject.class.getDeclaredFields();
and get target annotation from them :
Map<String, Set<String>> validationsRules = new HashMap<>();
Field field = fields[0]; // here you should iterate over all fields
Size size = field.getAnnotation(Size.class);
Set<String> dataAttributes = new HashSet<>();
dataAttributes.add("data-rule-minlength=" + size.min());
dataAttributes.add("data-rule-maxlength=" + size.max());
dataAttributes.add("data-msg-minlength=" + size.message());
dataAttributes.add("data-msg-maxlength=" + size.message());
validationsRules.put(field.getName(), dataAttributes);
The validation rules must be added to the view and attached to each field. Your final html will be something like this:
<input name="name" data-rule-minlength=2 data-rule-maxlength=30 data-msg-minlength="Invalid size" data-msg-maxlength="Invalid size"/>
Upvotes: 1