一个额外的警告框MVC3剃刀JQuery的客户端验证 [英] MVC3 Razor JQuery client side validation with an additional alert box

查看:105
本文介绍了一个额外的警告框MVC3剃刀JQuery的客户端验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被要求创建一个登录表单,当用户输入不通过验证它会弹出一个警告框。

I am being asked to create a login form that when the user input doesn't pass validation it pops an alert box.

我所拥有的一切线了使用基于模型的验证。

I have everything wire up using the model based validation.

例如:

 public class LogonViewModel
    {
        [Required( ErrorMessage = "User Name is Required")]
        public string UserName { get; set; }

        [Required( ErrorMessage = "Password is required")]
        public string Password { get; set; }
    }

我页面上的验证摘要:

I have a validation summary on the page:

Html.ValidationSummary()

我想总结在页面上以防万一用户有JavaScript的关闭。但是,如果客户端验证火灾我想也搭上了验证事件,并把错误变成警告框就像我被问。

I would like the summary to be on the page just in case the user has javascript off. But if the client side validation fires I want to also catch the validation event and put the errors into the alert box like I am being asked.

我的形式基本上是...

My form is basically ...

@Html.ValidationSummary()
 @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "loginForm" }))
     {
      username: @Html.TextBoxFor(m => m.UserName) <br/>
      password: @Html.TextBoxFor(m => m.Password) <br/>
      <input type="submit" value="Login"/>


    }

一个我想是事情

<script language="javascript">
        $(document).ready(function () {

            $("#loginForm").validate({
                invalidHandler: function (form, validator) {
                    var errors = validator.numberOfInvalids();
                    if (errors) {
                        alert(errors);
                    }
                }
            });
        });



    </script>

我无法弄清楚如何使这项工作。我只想让错误的正常验证和表现,但有机会做更多的只是有点。

I can't figure out how to make this work. I just want to allow the normal validation and showing of the errors but have the opportunity to do just a bit more.

推荐答案

一番搜索之后:

我发现这个添加InvalidHandler >
这使我这个解决方案:

I found this Add InvalidHandler after jQuery validator initialization Which lead me to this solution:

 $(document).ready(function () {
            $("#loginForm").bind('invalid-form.validate',
                function (form, validator) {
                    var errors = "Login failed:\r\n";

                    for (var i = 0; i < validator.errorList.length; i++) {
                        errors = errors + "\r\n\t-" + validator.errorList[i].message;    
                    }

                    alert(errors);


                }
                );
        });

这将运行正常的验证和更新验证总结,并设置所有样式,然后让我做额外的东西的后记。

This will run the normal validation and update the validation summaries and set all the styles and then allow me to do extra stuff afterword.

这篇关于一个额外的警告框MVC3剃刀JQuery的客户端验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆