我有一个MVC View ,其中包含使用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();
}
最佳答案
尝试将OnBegin回调添加到AjaxOptions并从该回调返回$('form')。validate()。form()的值。查看source似乎应该可以。
function ajaxValidate() {
return $('form').validate().form();
}
<% using (Ajax.BeginForm("Post", new AjaxOptions
{
UpdateTargetId = "GBPostList",
InsertionMode = InsertionMode.InsertBefore,
OnBegin = "ajaxValidate",
OnSuccess = "getGbPostSuccess",
OnFailure = "showFaliure"
}))
{ %>
使用正确的回调名称更新了。