问题描述
如何在ASP.NET Core MVC中触发客户端验证而不提交表单?
我正在使用模式,需要触发验证(无需提交表单)。
在jQuery中,我可以做到
$('#formID').validate().form()
但是,我想触发ASP .NET Core中包含的不打扰的验证。
解决方法
我认为我们可以使用以下代码:
public class Movie
{
public int Id { get; set; }
[Required]
[StringLength(100)]
public string Title { get; set; }
[ClassicMovie(1960)]
[DataType(DataType.Date)]
[Display(Name = "Release Date")]
public DateTime ReleaseDate { get; set; }
[Required]
[StringLength(1000)]
public string Description { get; set; }
[Range(0,999.99)]
public decimal Price { get; set; }
public Genre Genre { get; set; }
public bool Preorder { get; set; }
}
请检查this article
,ASP.NET Core仍然具有非干扰性验证,您只需要包括相关脚本即可。这是一个完整的例子。
假设此模型:
public class SomeViewModel
{
[Required]
public string Name { get; set; }
}
此控制器动作:
public IActionResult Index()
{
return View(new SomeViewModel());
}
最后,视图:
@model SomeViewModel
@{
ViewData["Title"] = "Home Page";
}
<form asp-action="Index" id="formID" method="post">
<input asp-for="Name" />
<span asp-validation-for="Name"></span>
<input type="submit" />
</form>
@section Scripts {
@{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
<script type="text/javascript">
$(function () {
// Silly example to demonstrate.
$('#formID').validate().form();
if ($('#formID').valid() === false) {
console.log("invalid");
} else {
console.log("valid!");
}
});
</script>
}
如果您查看~/Views/Shared/_ValidationScriptsPartial.cshtml
的内容,则会看到其中包含:
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
如果您在开发人员工具控制台中查看,它将在页面加载时立即验证表单,并在Name
文本框旁边显示必填字段缺少验证消息。