【发布时间】:2017-08-02 08:54:54
【问题描述】:
我是春季和前端的新手。 我有(不是我的)一个旧的前端代码,用于在某些页面上显示模态表单:
模态形式是:
<div id="myModalForm" class="modal inmodal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog ">
<div class="modal-content animated fadeIn">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span
aria-hidden="true">×</span><span class="sr-only"></span></button>
<h4 class="modal-title"><spring:message code="entity.modal.title"/></h4>
</div>
<div id="modalContent" class="modal-body">
<form id="createForm" name="createForm" class="" action="/entity/create"
method="post" enctype="multipart/form-data">
...
</form>
</div>
</div>
</div>
</div>
表单从 java 脚本中显示。调用表单的按钮是:
<script>
$(document).ready(function () {
$('#tbl').DataTable({
responsive: true,
dom: 'l<"toolbar">frtip',
initComplete: function () {
$("div.toolbar")
.html('<button id="new_entity_btn" type="button" class = "btn btn-white" onclick="openCreateWindow()" ><spring:message
code="entity.table.create.btn"/> </button>');
}
});
/*activate tooltips*/
$(function () {
$('[data-toggle="popover"]').popover();
});
});
</script>
onclick 按钮是:
<script>
function openCreateWindow() {
$('#myModalForm').modal('show');
}
</script>
现在您可以看到#myModalForm 不是 Spring 视图表单,因为它甚至不会生成要显示的 get-request。它只是以模式模式出现在现有页面上。现在的问题是如何为它创建 服务器端 验证?我试过了:
1) 将其重构为 spring mvc 形式,即通过
<form:form ... />
带有属性的标签
ModelAttribute='MyFormAttribute'。但我不知道如何为 MyFormAttribute 创建后端对象,因为表单的外观不会生成获取请求。想法是在控制器的 post 方法上有类似:
@RequestMapping(value = {"/entity/create"}, method = RequestMethod.POST)
String createNewEntity(
@ModelAttribute("MyFormAttribute") MyEntity entity,
BindingResult bindingResult,
Model model)
2) 尝试更改控制器的 post 方法,使其可能返回错误。但是如果表单不是 mvc one,则无法创建 bindingResult 参数
3) 尝试通过 jQuery.validate 进行验证,即 smth。喜欢:
<script>
/*form validation*/
$().ready(function () {
$("#createForm").validate({
rules: {
Field1: {
remote: function () {
var r = {
url: '/validateEntityField1',
type: "POST"
};
return r;
}
},
Field2: {
remote: function () {
var r = {
url: '/validateEntityField2',
type: "POST"
};
return r;
}
}
...
},
errorElement: "em",
highlight: function (element, errorClass, validClass) {
$(element).fadeOut(function () {
$(element).fadeIn();
});
$(element).addClass(errorClass).removeClass(validClass)
},
unhighlight: function (element, errorClass, validClass) {
$(element).removeClass(errorClass).addClass(validClass)
}
})
;
});
</script>
但它看起来相当难看,因为我应该在自己的端点上分别验证每个字段。除了表单有文件输入,所以我应该发送两次或smth。
那么,我该如何实现下一个问题:
- 在现有页面上保留模式表单
- 在服务器端验证它。对整个实体进行验证会很好。
【问题讨论】:
标签: spring validation spring-mvc jquery-validate