简体   繁体   English

如何使用服务器端验证生成客户端验证?

[英]How to generate client-side validations using server-side validations?

In my case, when server-side @Valid fails, the response contains error messages for each target input. 就我而言,当服务器端@Valid失败时,响应包含每个目标输入的错误消息。 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? 有没有办法使用服务器端验证生成客户端验证?

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. 如果您使用的是jQuery验证插件,则可以在每个字段上添加目标验证。 See reference for more details: https://jqueryvalidation.org/reference/ 有关更多详细信息,请参阅参考资料: 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: 你的最终HTML将是这样的:

<input name="name" data-rule-minlength=2 data-rule-maxlength=30 data-msg-minlength="Invalid size" data-msg-maxlength="Invalid size"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM