【问题标题】:Thymeleaf - Validation on collection of objectThymeleaf - 验证对象集合
【发布时间】:2018-01-29 02:38:15
【问题描述】:

我正在使用 thymeleaf 来显示我的网站。它是一个列出输入的表单。

<tr th:each="entry, stat : ${formWrapper.propertiesList}">
    <td> <label class="propertiesLabel" th:text="${entry.key}"/></label></td>
    <td> <input type="text" th:id="${entry.key}" th:field="*{propertiesList[__${stat.index}__].value}"></input></td>
</tr>

在我的模型中,我的表单包含这些对象。

public form(String key, String value){
    super();
    this.key = key;
    this.value = value;
}

//getter amd setter methods

我还有一个包装器来包装表单。

public ArrayList<Form> getPropertiesList(){
    return propertiesList;
}

public void setPropertiesList(ArrayList<Form> properties){
    this.propertiesList = properties;
}

有人有任何方法来验证输入值列表吗?通过javascript(前端)或Java(后端)对我有好处。

【问题讨论】:

    标签: javascript java spring validation thymeleaf


    【解决方案1】:

    您可以使用休眠验证器在后端验证Form。您只需使用所需的任何验证来注释Form 的属性。 @NotNull 注释验证键和值不为空。如果它恰好为 null,它将返回与其关联的消息。 @Size 注解验证 key 和 value 的最大大小分别为 20 和 30。如果恰好超过指定的限制,则返回与之关联的消息。

    public class Form {
        @NotNull(message = "Key cannot be null")
        @Size(max = 20,message = "Maximum size is 20")
        private String key;
        @NotNull(message = "value cannot be null")
        @Size(max = 30,message = "Maximum size is 30")
        private String value;
    
        //getters and setters
    }
    

    然后您可以在处理函数中检查有效性,如

    @RequestMapping(value = "/saveForm",method = RequestMethod.POST)
    public void saveForm(@Valid Form form,BindingResult bindingResult){        
        if(bindingResult.hasErrors()){            
            // bindingResult.getAllErrors() gets you all the errors. Now handle it
        }        
    }
    

    【讨论】:

    • 嗨@Vyshak,感谢您的回答。如果输入中的每个值都需要进行不同的验证,例如:输入 A 仅是文本,输入 B 仅是整数等等……还能做到吗?
    • @Ken.T 是的,可以做到。例如,如果输入 B 仅为整数,则可以使用 @Pattern(regexp = "\\d+",message = "Only numbers are allowed")。输入 A 也可以这样做。只需使用适当的正则表达式即可。
    猜你喜欢
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-01
    • 2011-05-05
    • 1970-01-01
    相关资源
    最近更新 更多