[英]How to generate client-side validations using server-side validations?
就我而言,當服務器端@Valid
失敗時,響應包含每個目標輸入的錯誤消息。 所以我不必編寫客戶端驗證。 但我想事先使用客戶端驗證來最小化請求。 但是我很懶,我發現自己編碼兩次基本相同。
有沒有辦法使用服務器端驗證生成客戶端驗證?
如果您在服務器端使用注釋進行驗證,則可以基於它們生成客戶端驗證。
例如:
public class MyObject{
@Size(min=2, max=30, message ="Invalid size")
private String name;
//getters & setters
}
如果您使用的是jQuery驗證插件,則可以在每個字段上添加目標驗證。 有關更多詳細信息,請參閱參考資料: https : //jqueryvalidation.org/reference/
您可以獲取所有字段並查看其注釋:
Field[] fields = MyObject.class.getDeclaredFields();
並從中獲取目標注釋:
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);
必須將驗證規則添加到視圖並附加到每個字段。 你的最終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.