我使用了来自http://struts.jgeppert.com/struts2-jquery-showcase/index.action和http://code.google.com/p/struts2-jquery/wiki/Validation的标准代码片段。
但是客户端和 ajax 服务器端验证不能一起工作。
问题是表单提交不会停止,并且即使我们preventDefault
或执行其他任何操作也会调用操作。
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="sj" uri="/struts-jquery-tags"%>
<html>
<head>
<sj:head jqueryui="true"/>
</head>
<body>
<div id="result">
<s:actionerror/>
<s:fielderror fieldName="name" value="eroor"></s:fielderror>
Submit form bellow.</div>
<!-- A List for Global Error Messages -->
<ul id="formerrors" class="errorMessage"></ul>
<s:form id="formValidateCustom" action="register1.action" namespace="/" theme="simple" cssClass="yform" >
<fieldset>
<legend>AJAX Form with Validation</legend>
<div class="type-text">
<label for="echo">User: <span id="loginuserError"></span></label>
<sj:textfield id="name" name="name" />
</div>
<div class="type-text">
<label for="echo">Password: <span id="loginpasswordError"></span></label>
<sj:textfield id="password" name="password" />
</div>
<div class="type-button">
<sj:submit
targets="result"
button="true"
validate="true"
validateFunction="customeValidation"
value="Submit"
onBeforeTopics="before"
timeout="2500"
indicator="indicator"
/>
</div>
</fieldset>
</s:form>
<script type="text/javascript">
function customeValidation(form, errors) {
//List for errors
// alert("in js");
var list = $('#formerrors');
//Handle non field errors
if (errors.errors) {
$.each(errors.errors, function(index, value) {
list.append('<li>'+value+'</li>\n');
});
}
//Handle field errors
if (errors.fieldErrors) {
$.each(errors.fieldErrors, function(index, value) {
var elem = $('#'+index);
if(elem)
{
alert(value[0]);
}
});
}
}
$.subscribe('before', function(event,data) {
var fData = event.originalEvent.formData;
alert('About to submit: \n\n' + fData[0].value + ' to target '+event.originalEvent.options.target+' with timeout '+event.originalEvent.options.timeout );
var form = event.originalEvent.form[0];
if (form.name.value.length < 2) {
alert('Please enter a value with min 2 characters');
**// the event does not stop here if we use ajax validation i.e validate = true, if we remove it then this works.**
event.originalEvent.options.submit = false;
}
});
</script>
</body>
</html>
event.originalEvenet.options.submit = false 如果我们在提交按钮中使用 ajax 验证,即 validate = true,则不会在此处停止,如果我们将其删除,则此方法有效。**