我在MVC应用程序中使用jquery验证,在选择并保留输入后,它会自动验证。另一方面,如果用户未选择输入,即使提交表单,也不会验证它们。所以,我想在按下MVC Razor页面上的提交按钮后验证所有相关字段。我怎么能这样做?
答案 0 :(得分:6)
我创建了一个简单的例子。它只是为您提供一个开始,您仍然需要根据您的需要修改此代码。此示例使用jquery表单验证。
<强>模型强>
public class Vehicle
{
public int Id { get; set; }
public string Make { get; set; }
public string Model { get; set; }
}
控制器&amp;操作强>
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
查看强>
@model JqueryValidationDemo.Models.Vehicle
@{
ViewBag.Title = "Jquery Form Validation Demo";
}
<script src="~/Scripts/jquery-2.0.3.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script>
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
Make: {
required: true,
minlength: 2
},
Model: { required: true }
},
messages: {
Make: {
required: "Make is required!",
minlength: "Make Name at least 2 characters long!"
},
Model: {
required: "Modl is required!"
}
},
submitHandler:
$("#myform").on('submit', function () {
if ($("#myform").valid()) {
//Do something here
alert("Validation passed");
}
return false;
})
})
});
</script>
@using (Html.BeginForm("Index", "Home", FormMethod.Get, new { @id = "myform" }))
{
<fieldset>
<legend>Vehicle</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Make)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Make)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Model)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Model)
</div>
<p>
<input type="submit" value="Submit" />
</p>
</fieldset>
}
注意:小心你的jquery引用,你不需要使用jquery.validate.unobtrusive.js。
希望它会给你一个良好的开端。
<强>更新强> 删除keyup或按键
删除按键
$("#youElementId").bind('keypress', function (e) {
if (e.keyCode == 13) {
return false;
}
return true;
});