Search code examples
jqueryajaxasp.net-mvcvalidationunobtrusive-validation

How to validate a textboxfor field with jquery and no form?


I want to know how I can activate the jquery unobtrusive validation when I got no form and with this pattern :

    <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>

The 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" })

If I had a form, I could use the form.valid(), but I don't know about that use case when I got a textboxfor only.

Thanks,

David

-- Edit

I forgot to mention this very important detail: Here the validation I got on the textboxfield:

<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="">

Solution

  • Finally, here the solution. If you set up a regex rule on the server side, you can still retrieve the regex pattern with jquery this way and do the validation manually.

    <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
           ......
        }
    });