我整天都在为此苦苦挣扎。我需要验证表单,如果有效,请使用 ajax 调用提交。从我读过的内容来看,一旦发生所有验证,包括远程检查,submitHandler 应该会触发。
当我输入一个已经存在的用户名时,我收到了'User Name already exists'
消息,并且没有像预期的那样调用 submitHandler。但是,如果任何其他验证检查失败,表单会正常发布到表单操作 url,并且 submitHandler 回调似乎永远不会被调用。
希望有人能看到我做错了什么:
<form id="addUserForm">
<table class="table table-striped table-bordered">
<thead class="text-warning">
<tr>
<th>User Name</th>
<th>Password</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>
<th>User Type</th>
<th class="center">Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" value="" name="username" id="Name" class="span12">
</td>
<td>
<input type="password" value="" name="password" id="Password" class="span12">
</td>
<td>
<input type="text" value="" name="forename" id="FirstName" class="span12">
</td>
<td>
<input type="text" value="" name="surname" id="LastName" class="span12">
</td>
<td>
<input type="text" value="" name="email" id="Email" class="span12">
</td>
<td>
<select name="Type" class="span12" id="Type">
<option>Administrator</option>
<option selected="selected">Standard</option>
<option>Surveyor</option>
</select>
</td>
<td class="center">
<button class="btn" id="btnAdd">Add</button>
</td>
</tr>
</tbody>
</table>
</form>
<script>
$(document).ready(function () {
$('#addUserForm').validate({
onsubmit: true, onfocusout: false, onkeyup: false, onclick: false, errorPlacement: function (error, element) { },
invalidHandler: function (event, validator) {
if (validator.errorList.length) {
alert(validator.errorList[0].message);
validator.errorList[0].element.focus();
}
},
rules: {
username: { required: true, remote: '/admin/isusernameavailable' },
password: { required: true },
forename: { required: true },
surname: { required: true },
email: { required: true, email: true }
},
messages: {
username: { required: 'User Name is required', remote: 'User Name already exists' },
password: { required: 'Password is required' },
forename: { required: 'First Name is required' },
surname: { required: 'Last Name is required' },
email: { required: 'Email Address is required', email: 'Email Address is invalid' }
},
submitHandler: function (form) {
// create the data object
var data = {
Name: $('#Name').val(),
Password: $('#Password').val(),
FirstName: $('#FirstName').val(),
LastName: $('#LastName').val(),
Email: $('#Email').val(),
Type: $('#Type').val()
}
// post the form
var posting = $.post('/admin/adduser', data);
// post success
posting.done(function (data) {
// display the results
$('#results').html(data);
$('#Name').val('');
$('#Password').val('');
$('#FirstName').val('');
$('#LastName').val('');
$('#Email').val('');
$('#Type').val('Standard');
});
// post error
posting.fail(HandlePostFailError);
}
});
});
</script>