【发布时间】:2010-09-22 20:35:32
【问题描述】:
我有一个 MVC 视图,其中包含使用 Ajax.BeginForm() 辅助方法构建的表单,我正在尝试使用 jQuery Validation plugin 验证用户输入。我让插件突出显示输入数据无效的输入,但尽管输入无效,但表单仍会发布到服务器。
我如何停止这种情况,并确保仅在表单验证时才发布数据?
我的代码
形式:
<fieldset>
<legend>leave a message</legend>
<% using (Ajax.BeginForm("Post", new AjaxOptions
{
UpdateTargetId = "GBPostList",
InsertionMode = InsertionMode.InsertBefore,
OnSuccess = "getGbPostSuccess",
OnFailure = "showFaliure"
}))
{ %>
<div class="column" style="width: 230px;">
<p>
<label for="Post.Header">
Rubrik</label>
<%= Html.TextBox("Post.Header", null, new { @style = "width: 200px;", @class="text required" }) %></p>
<p>
<label for="Post.Post">
Meddelande</label>
<%= Html.TextArea("Post.Post", new { @style = "width: 230px; height: 120px;" }) %></p>
</div>
<p>
<input type="submit" value="OK!" /></p>
</fieldset>
JavaScript 验证:
$(document).ready(function() {
// for highlight
var elements = $("input[type!='submit'], textarea, select");
elements.focus(function() {
$(this).parents('p').addClass('highlight');
});
elements.blur(function() {
$(this).parents('p').removeClass('highlight');
});
// for validation
$("form").validate();
});
编辑:当我因发布后续问题及其答案中的解决方案而遭到否决时,这也是有效的验证方法...
function ajaxValidate() {
return $('form').validate({
rules: {
"Post.Header": { required: true },
"Post.Post": { required: true, minlength: 3 }
},
messages: {
"Post.Header": "Please enter a header",
"Post.Post": {
required: "Please enter a message",
minlength: "Your message must be 3 characters long"
}
}
}).form();
}
【问题讨论】:
标签: jquery asp.net-mvc ajax validation