Client-side MVC3 Razor JQuery validation with optional alert field

I am prompted to create a login form, when user input fails validation, a warning window appears.

I have all postings using model-based validation.

Example:

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 only if the user has javascript disabled. But if the client-side check is triggered, I also want to catch the check event and put the errors in the notification window, as if they were asking me.

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 do this. I just want to allow normal error checking and display, but I have the opportunity to do a little more.

+1
source share
3 answers

After a long search:

I found this Add InvalidHandler after initializing the jQuery validator Which led 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 start a regular check and update the validation summaries and set all the styles, and then allow me to do an extra afterword.

0
source

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

+1
source

It 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 } }); } 
0
source

All Articles