我想知道当我没有任何形式并使用这种模式时,如何激活jquery不显眼的验证:
<script type="text/javascript">
$('.btnAddAsync').click(function (e) {
e.preventDefault(); // Avoid href postback
var $letter = $(this);
var charityAmount = $(".charity-gift");
// *******
// IF charityAmount IS VALID based on the unobtrusive rule then do the following
// *******
var href = charityAmount.attr('data-href');
href = href.replace(/(charityGiftAmount=)[0-9]+/ig, '$1' + $(".charity-gift").val());
......
});
</script>
HTML:
<div class="row">
<div class="col-lg-12">
<div class="input-group">
@Html.TextBoxFor(m => item.CharityGiftAmount, new { @class = "charity-gift form-control", data_href = Url.Action("Add", "Checkout", new { eventSlug = Model.Slug, eventId = Model.Id, skuId = item.Id, quantity = 1, charityGiftAmount = 0 }) })
<span class="input-group-btn">
<button class="btn btn-default btnAddAsync" type="button">@SharedResources.AddToCart</button>
</span>
</div>
</div>
</div>
@Html.ValidationMessageFor(m => item.CharityGiftAmount, "", new { @class = "text-danger" })
如果我有一个表单,我可以使用form.valid()
,但是当我得到一个文本框时,我不知道该用例。
谢谢,
大卫
- 修改
我忘了提到这个非常重要的细节: 这是我在textboxfield上得到的验证:
<input class="charity-gift form-control" data-href="/Checkout/Add?eventSlug=trail-and-donation&eventId=4&skuId=5&quantity=1&charityGiftAmount=0" data-val="true" data-val-regex="Invalid amount" data-val-regex-pattern="^(\d+(?:[\.\,]\d{2})?|)$" id="item_CharityGiftAmount" name="item.CharityGiftAmount" type="text" value="">
答案 0 :(得分:0)
最后,这里是解决方案。 如果在服务器端设置了正则表达式规则,仍然可以使用jquery以这种方式检索正则表达式模式,并手动进行验证。
<script type="text/javascript">
$('.btnAddAsync').click(function (e) {
var charityAmount = $(".charity-gift");
var validationRule = new RegExp(charityAmount.attr('data-val-regex-pattern'));
if (validationRule.test(charityAmount.val())) {
// Regex passed
var href = charityAmount.attr('data-href');
href = href.replace(/(charityGiftAmount=)[0-9]+/ig, '$1' + $(".charity-gift").val());
......
}
else {
// Regex failed
......
}
});