10

I've got a model that does some validation checking and adds the errors to ModelState:

ViewData.ModelState.AddModelError("mycontrol", "message")

They display fine on the view side, but is there a way to set the focus to the control that corresponds to the validation message? Right now, the page refreshes and stays at the top of the page, so if the error is towards the end of the page, it's not obvious to the user what happened.

Note: Another solution would be for ValidationSummary to show the list of errors at the top of the page, but I've never been able to get it to display anything. All my errors are displayed via ValidationMessage.

Edit: I found my problem with ValidationSummary. The markup I had was:

<% Html.ValidationSummary()%>

which should have been:

<%=Html.ValidationSummary()%>

I'd still like to know how to snap to the field with the error however.

2
  • ValidationSummary should be working. It does for me. Can you show us some of your mark up (perhaps simplified by omitting static html)? The HtmlHelper extension looks at the same model state to render the errors.
    – tvanfosson
    Apr 7, 2009 at 13:36
  • I got halfway through posting my sample code when I noticed the missing "=" in the markup (and placed open palm to forehead).
    – gfrizzle
    Apr 7, 2009 at 15:31

2 Answers 2

37

Some jquery goodness to scroll to the first input with an error. The tricky bit is that you have to get the underlying DOM element BEFORE you invoke focus() as the focus() method on a jQuery object fires the focus event instead of giving focus to the element.

<script type='text/javascript'>
    $(document).ready( function()
    {
       var input = $('.input-validation-error:first');

       if(input)
       {
           input.focus();
       }
    });
</script>
2
  • Good solution. I just had to add "return false" to make it work. if(input) { input.focus(); return false; } Sep 18, 2015 at 8:38
  • @HallgeirEngen that really should not be necessary. All it will do is abort the execution of the ready handler. If you have any code after that, it won't be executed.
    – tvanfosson
    Sep 18, 2015 at 13:59
1

You could use JavaScript to find the input elements on the page that have the MVC validation HTML class (input-validation-error) added, and move the carat to the first one. That /should/ move the screen to that element although I haven't tested it.

A JS library such as jQuery will make this straightforward to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.