我已经创建了一个表单,我正在使用jQuery验证,我需要移动两个字段的错误消息,所以我在这里找到了一个示例,说明如何做到这一点并且它工作得很好。除此之外,现在,“必填”字段并非全部有效。这是我的表单代码:
<form id="myForm">
<div class="form-group">
<label for="x_po_num">Account Number</label>
<input type="text" class="form-control" name="x_po_num" id="x_po_num">
</div>
<div class="form-group">
<label for="x_invoice_num">Invoice Number</label>
<div class="input-group">
<div class="input-group-addon">9</div>
<input class="form-control" name="x_invoice_num" id="x_invoice_num" data-error="#invError">
</div>
<div id="invError"></div>
</div>
<div class="form-group">
<label for="x_reference_3">Reference Number</label>
<input class="form-control" name="x_reference_3" id="x_reference_3" placeholder="Optional" >
</div>
<div class="form-group">
<label for="x_amount">Amount</label>
<div class="input-group">
<div class="input-group-addon">$</div>
<input class="form-control" name="x_amount" id="x_amount" data-error="#amtError">
</div>
<div id="amtError"></div>
</div>
<input class="btn btn-primary" value="Pay With Your Credit Card" type="submit">
</form>
这是我的jQuery验证代码:
$( "#myForm" ).validate({
rules: {
x_po_num: {
required: true,
digits: true,
minlength: 11,
maxlength: 11
},
x_invoice_num: {
required: true,
digits: true,
maxlength: 9,
minlength: 7,
normalizer: function( value ) {
var inv = value;
inv = "9" + inv;
return inv;
}
},
x_reference_3: {
digits: true,
maxlength: 9,
},
x_amount: {
required: true,
number: true
}
},
messages: {
x_po_num: {
required: "Please enter an account number",
minlength: "The account number must be 11 digits long",
maxlength: "The account number must be 11 digits long",
digits: "Please enter digits only, no spaces"
},
x_invoice_num: {
required: "Please enter an invoice number",
maxlength: "The invoice number must be 10 digits or less",
minlength: "The invoice number must be at least 8 digits long",
digits: "Please enter digits only, no spaces"
},
x_reference_3: {
digits: "Please enter digits only",
maxlength: "The reference number must be 9 digits or less"
},
x_amount:{
required: "Please enter an amount"
}
},
errorPlacement: function(error, element) {
var placement = $(element).data('error');
if (placement) {
$(placement).append(error)
} else {
error.insertAfter(element);
}
}
});
这是问题所在:
我需要移动错误消息的两个字段(发票编号和金额)现在位于正确的位置。但是,如果我打开表单并点击提交而不输入任何数据,我预计发票编号会出现错误,上面写着“请输入发票编号”,但事实并非如此。它根本不显示任何错误。
原来它是规范化器功能。我把它拿出来并用我的onSubmit添加了数字并解决了问题。