我有一个以模式打开的表单。我想为此实现验证。但是,我尝试实现 jQuery 表单验证但徒劳无功。无法触发表单验证的主要原因是表单提交按钮是使用javascript触发的。当表单提交时,它不执行验证部分。
解决这个问题的方法是什么?
这是表格::
<div id="__paymentModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Make Payment Request</h3>
</div>
<div class="modal-body">
<form method="post" action="" id="__paymentForm" class="form-horizontal">
<input type="text" name="name" value="" placeholder="Payee Name">
<input type="text" name="phone" value="" placeholder="Phone"/>
<input type="text" name="address" value="" placeholder="Address"/>
<input type="text" name="pincode" value="" placeholder="Pincode" />
<input type="text" name="amount" value="" placeholder="Amount"/>
</form>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true" onclick="javascript: reset()">Close</button>
<button class="btn btn-primary" onclick="javascript: sendPaymentRequest()">Save changes</button>
</div>
</div>
以及触发表单提交的 JavaScript。
var paymentReqBttnObject = undefined;
function reset() {
window.paymentReqBttnObject = undefined;
}
function openModalForPaymentReq(ele) {
$('#__paymentForm input[type="text"]').val("");
$('#__paymentModal').modal( { backdrop: false });
window.paymentReqBttnObject = ele;
}
function sendPaymentRequest() {
$.ajax({
type: "post",
url: url,
data: $('#__paymentForm').serialize(),
processData : true,
dataType: 'html',
beforeSend: function() {
$('#__paymentModal').hide();
},
success: function(data, textStatus, xhr) {
var json = $.parseJSON(data);
if(json.success == "request_made") {
$(paymentReqBttnObject).addClass("btn-requested").html("Payment Requested");
$(paymentReqBttnObject).unbind("click");
} else {
}
window.reset();
},
error: function(xhr, textStatus, errorThrown) {
window.reset();
}
});
}
我还尝试了 jquery 表单验证器,但在提交表单时仍然没有显示任何错误。它立即进入仅更新空值的数据库。
验证 jQuery
$(document).ready(function(){
$("#__paymentForm").validate({
rules: {
phone: { //input name: fullName
required: true, //required boolean: true/false
minlength: 10,
maxlength: 10
},
address: {
required: true
},
pincode: {
required: true,
minlength: 6,
maxlength: 6
}
amount: {
required: true
}
},
messages: { //messages to appear on error
phone: { //input name: fullName
required: "Your Phone Number", //required boolean: true/false
minlength: "Correct contact number.",
maxlength: "Correct contact number."
},
address: {
required: "Where to collect money."
},
pincode: {
required: "Pincode is required to locate the city and all others.",
minlength: "Correct Pincode Please.",
maxlength: "Correect Pincode Please"
}
amount: {
required: "What is the amount."
},
},
submitHandler: function(form) {
$(form).ajaxSubmit({
success: function(){
alert('inside');
}
});
}
});
})