jQuery 验证错误放置和所需的文本放置
Posted
技术标签:
【中文标题】jQuery 验证错误放置和所需的文本放置【英文标题】:jQuery Validate error placement and required text placement 【发布时间】:2019-08-05 19:12:52 【问题描述】:我创建了一个使用 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);
);
问题出在这里:
我需要移动错误消息的两个字段(发票编号和金额)现在位于正确的位置。但是,如果我打开表单并在不输入任何数据的情况下点击提交,我预计发票编号会出现错误,显示“请输入发票编号”,但事实并非如此。它根本不显示任何错误。
【问题讨论】:
【参考方案1】:原来是归一化函数。我把它拿出来,用我的 onSubmit 添加数字,问题就解决了。
【讨论】:
以上是关于jQuery 验证错误放置和所需的文本放置的主要内容,如果未能解决你的问题,请参考以下文章
启用/禁用使用 JQuery 禁用输入的 ASP.NET Web 表单所需的验证器?