MVC3 Razor JQuery client side validation with an a

2019-08-07 04:40发布

问题:

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.

ex:

 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()

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"/>


    }

One of the things I tried was

<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.

回答1:

One solution would be to modify the onErrors function in jquery.validate.unobtrusive.js. The function is very readable.



回答2:

After much searching:

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.



回答3:

This Worked for me...

var settings = $.data($('form')[0], 'validator').settings;

if (jQuery.validator) {
    jQuery.validator.setDefaults({
        showErrors: function (errorMap, errorList) {
            $.extend($.validator.defaults, settings);
            var message = '';
            for (var i = 0; i < errorList.length; i++) {
                message += errorList[i].message + '\n\n';
            }

            alert(message);//Replace your modal popup here
        }
    });
}