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.
One solution would be to modify the onErrors function in jquery.validate.unobtrusive.js. The function is very readable.
This Worked for me...
After much searching:
I found this Add InvalidHandler after jQuery validator initialization Which lead me to this solution:
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.