.Net Mvc 3 Trigger (other than submit button) Unobtrusive Validation

南楼画角 提交于 2019-11-28 07:15:00

$('form').valid() should work. Let's exemplify.

Model:

public class MyViewModel
{
    [Required]
    public string Foo { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }
}

View:

@model MyViewModel

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

@using (Html.BeginForm())
{
    @Html.LabelFor(x => x.Foo)
    @Html.EditorFor(x => x.Foo)
    @Html.ValidationMessageFor(x => x.Foo)
}

<div id="validate">Hover here to trigger validation</div>

<script type="text/javascript">
    $('#validate').hover(function () {
        $('form').valid();
    });
</script>

Manual validation of custom messages injected directly to HTML

@{using (Html.BeginForm("addBuyOnlinepostA", "BuyOnline", FormMethod.Post, new { @enctype = "multipart/form-data", @id = "form1" }))
  {

    @Html.ValidationSummary(true)

    <div class="row">
        <div class="col-sm-10">
            Product Qty
            <input class="inputs" required type="number" id="price" name="price" placeholder="Enter Price in AED"
                data-val="true" data-val-required="Please enter a value" data-val-regex="Please enter a valid number."
                data-val-regex-pattern="\d{1,20}" />
            <span class="field-validation-valid" data-valmsg-for="price" data-valmsg-replace="true"
                style="color: Red;"></span>
        </div>
    </div>   



    <input type="button" onclick="$('form').valid()" />

  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!