MVC 3 和 JQuery 中的手动表单验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5054328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Manual form validation in MVC 3 and JQuery
提问by Mike Barlow - BarDev
I want to be able to trigger form validation on the client side when the user selects the "GO" button. Currently when the "GO" button is selected it does not validate the complete form. For example, If I load the form and select the "Go" button without giving focus to the text box, nothing is validated and val.Valid() returns true. If I do enter invalid data in a text box, validation is ran for that individual item; and when I select the "GO" button, val.Valid() return false.
当用户选择“GO”按钮时,我希望能够在客户端触发表单验证。目前选择“Go”按钮时,它不会验证完整的表单。例如,如果我加载表单并选择“Go”按钮而不将焦点放在文本框上,则不会验证任何内容并且 val.Valid() 返回 true。如果我确实在文本框中输入了无效数据,则会对该单个项目运行验证;当我选择“GO”按钮时,val.Valid() 返回 false。
So what I'm trying to do, is when a user select a button or other event, I want to trigger all the forms validation.
所以我想要做的是,当用户选择按钮或其他事件时,我想触发所有表单验证。
I'm doing this in MVC 3
我在 MVC 3 中这样做
public class TestValidationModel
{
[Required(ErrorMessage="UserName Is Required")]
[RegularExpression(@"(\S)+", ErrorMessage = "White space is not allowed")]
[StringLength(12, MinimumLength = 3)]
public string UserName { get; set; }
[Required(ErrorMessage="Password Is Required")]
[StringLength(20, MinimumLength = 3)]
public string Password { get; set; }
[Required(ErrorMessage="Email Address Is Required")]
[Display(Name = "Email Address")]
public string EmailAddress{ get; set; }
}
<script src="/BasicMvc3Example2/Scripts/jquery-1.4.4.js" type="text/javascript"></script>
<script src="/BasicMvc3Example2/Scripts/jquery-ui.js" type="text/javascript"></script>
<script src="/BasicMvc3Example2/Scripts/jquery.validate.js" type="text/javascript"></script>
<script src="/BasicMvc3Example2/Scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#butValidateForm").click(function(){
var val = $('#myForm').validate()
alert(val.valid());
})
});
</script>
@using (Html.BeginForm("", "", FormMethod.Post, new {id = "myForm"}))
{
<div>
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName)
@Html.ValidationMessageFor(m => m.UserName)
</div>
<div>
@Html.LabelFor(m => m.Password)
@Html.TextBoxFor(m => m.Password)
@Html.ValidationMessageFor(m => m.Password)
</div>
<div>
@Html.LabelFor(m => m.EmailAddress)
@Html.TextBoxFor(m => m.EmailAddress)
@Html.ValidationMessageFor(m => m.EmailAddress)
</div>
<button id="butValidateForm">GO</button>
<input type="submit" id="submitForm" value="Submit" />
}
Update
更新
I think I found the solution to my problem. See showErrors Below
我想我找到了解决问题的方法。请参阅下面的显示错误
<script type="text/javascript">
$(function () {
$("#butValidateForm").click(function () {
var val = $('#myForm').validate();
val.showErrors(); //<-- Call showErrors
alert(val.valid());
})
});
</script>
This following link to the post on JQuery forms did not pertain to my problem, but I was able to find the method names I was looking for. http://plugins.jquery.com/content/jqueryvalidate-showerrors-issue-form-wizard
下面这个链接到 JQuery 表单上的帖子与我的问题无关,但我能够找到我正在寻找的方法名称。 http://plugins.jquery.com/content/jqueryvalidate-showerrors-issue-form-wizard
If someone has a better answer, please provide feedback.
如果有人有更好的答案,请提供反馈。
Update
更新
The previous code somewhat works in Firefox, but not at all in IE. I did the following and it works now in Firefox but still not in ID
前面的代码在 Firefox 中有些工作,但在 IE 中根本不起作用。我做了以下操作,它现在可以在 Firefox 中使用,但仍然不能在 ID 中使用
$(function () {
$("#myForm").submit(function (e) {
var val = $('#myForm').validate(); //<--added the semi-colon
val.showErrors();
alert(val.valid());
e.preventDefault();
});
});
// $("#butValidateForm").click(function () {
// var val = $('#myForm').validate()
// val.showErrors();
// alert(val.valid());
// })
});
Thanks for Using jQuery To HiHyman ASP.NET MVC Form Postsfor pointing me in the correct direction. But still not perfect
感谢使用 jQuery 劫持 ASP.NET MVC 表单帖子为我指明了正确的方向。但仍然不完美
回答by Mike Barlow - BarDev
I don't know if this is the best/most efficient way, but I do it by validating each element individually in my own function.
我不知道这是否是最好/最有效的方法,但我通过在我自己的函数中单独验证每个元素来做到这一点。
jQuery(document).ready(function () {
$("#butValidateForm").button().click(function () { return IsMyFormValid(); });
$('#myForm').validate();
}
function IsMyFormValid() {
var isValid = false;
isValid = $('#myForm').validate().element($('#UserName '));
isValid = ($('#myForm').validate().element($('#Password '))) ? isValid : false;
isValid = ($('#myForm').validate().element($('#EmailAddress'))) ? isValid : false;
return isValid;
}
It would be great to let it validate automagically, but I always seem to run into some weird business logic rule that doesn't get caught by the generic validation methods. Doing it this way lets me control all of the validation the way I want to, but relying on built in validation most of the time.
让它自动验证会很棒,但我似乎总是遇到一些奇怪的业务逻辑规则,这些规则不会被通用验证方法捕获。这样做可以让我以我想要的方式控制所有验证,但大多数时候依赖于内置验证。
回答by Adamy
<script type="text/javascript">
$(function () {
$("#butValidateForm").click(function (event) {
var isValid = $('#myForm').valid();
if(isValid)
{
//do something before submit the form
$('#myForm').submit();
}else{
alert('validation failed');
}
event.preventDefault();
})
});
</script>
回答by Martin
Not sure if you figured this out yet, but I ran into the same thing in IE with $("#myForm").submit
. Use live
:
不确定你是否已经解决了这个问题,但我在 IE 中遇到了同样的事情$("#myForm").submit
。使用live
:
$("#myForm").live('submit', function (e) {
var val = $('#myForm').validate(); //<--added the semi-colon
val.showErrors();
alert(val.valid());
e.preventDefault();
});
回答by John Farrell
Its not working in IE because you are missing a semi-colon:
它在 IE 中不起作用,因为您缺少分号:
var val = $('#myForm').validate()