【问题标题】:How to validate a textboxfor field with jquery and no form?如何使用 jquery 验证 textboxfor 字段而没有表单?
【发布时间】:2017-02-13 20:46:46
【问题描述】:

我想知道当我没有表单并且使用这种模式时如何激活 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(),但是当我只有一个文本框时我不知道那个用例。

谢谢,

大卫

-- 编辑

我忘了提到这个非常重要的细节: 这是我在文本框字段上得到的验证:

<input class="charity-gift form-control" data-href="/Checkout/Add?eventSlug=trail-and-donation&amp;eventId=4&amp;skuId=5&amp;quantity=1&amp;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="">

【问题讨论】:

  • 您需要什么验证?只是想知道是否填写了吗?
  • 看起来您需要获取charity-gift 的值。那你需要把var charityAmount = $(".charity-gift");改成var charityAmount = $(".charity-gift").val();
  • 请看我的编辑
  • @CesarBielich:我想触发正则表达式验证:data-val-regex-pattern="^(\d+(?:[\.\,]\d{2})?|) $"

标签: jquery ajax asp.net-mvc validation unobtrusive-validation


【解决方案1】:

最后,这里是解决方案。 如果您在服务器端设置了正则表达式规则,您仍然可以通过这种方式使用 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
       ......
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 2018-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多