Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move focus to first error field with MVC client validation?

I use MicrosoftMvcValidation.js for client side validation. Error messages show correct. However, my page is kind of long and when the error shows, it does not automatically scroll up to show the 1st error message or set focus to error field. How can I show a message beside button like "Error happens. Please correct your input", but without list of field errors; or automatically move focus to 1st error field?

like image 797
Jing Avatar asked Jun 25 '11 01:06

Jing


People also ask

How do you handle validation in MVC?

In code we need to check the IsValid property of the ModelState object. If there is a validation error in any of the input fields then the IsValid property is set to false. If all the fields are satisfied then the IsValid property is set to true. Depending upon the value of the property, we need to write the code.

How client side validation is implemented in MVC?

Firstly, you just need to create an ASP.NET MVC application. To create a new ASP.NET MVC application, Open Visual Studio choose File, New, then Project. It will open a New Project window, from where you need to choose node Visual C# and then Web and from the right pane you need to choose ASP.NET Web Application.


1 Answers

Whenever you have validation error, client-side validation will add input-validation-error class to those input boxes that caused validation. For example, in MVC3 if you have unobtrusive validation enabled you will get additional javascript files added to your file, like

<script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>

This means that you can use your own jQuery functions after these lines that would detect whether input-validation-error exists or not. This piece of code is something that I am using in my applications:

$(document).ready(function () {
    $("form[action*='New/']").submit(function () {
        var firstError = $(this).children(":first has('.input-validation-error')");

        if (firstError != null) {
            firstError.focus();

            return false; // no form posting
        }
    });
});

Replace the form[action*='New/'] with your form action, e.g. form[action*='/MyController/MyRegistrationAction/'] (*= means find this text at any location).

like image 162
Husein Roncevic Avatar answered Sep 28 '22 09:09

Husein Roncevic