Anton
Anton

Reputation: 1386

ASP MVC4 unobtrusive validation with regex doesn't set focus on invalid field

The simplified case is that I have a form with two fields, one takes a zip code, the other an e-mail address.

They are backed by a edit model that contains this:

[Required(ErrorMessage = "Mandatory")]
[Range(10000, 99999, ErrorMessage = "Error bla bla...")]
public string ZipCode{ get; set; }

[Required(ErrorMessage = "Mandatory", AllowEmptyStrings = false)]
[StringLength(64, ErrorMessage = "Error bla bla")]
[RegularExpression(EmailRegEx, ErrorMessage = "Error bla bla")] //EmailRegEx is a const string
public string ContactEmail { get; set; }

Here's the problem. When the validation fires after clicking the submit button and an error is found in the zip code field, focus is set on the invalid field. However, when the email with the regex fails, focus is still on the submit button. This is tested in Chrome 31, Win7.

I'm using jQuery Validation Plugin - v1.11.1 and jquery.validate.unobtrusive.js (MVC4). I've tried this too, hooking into the event handler, but it doesn't work either:

$(document).ready(function () {
        $("#myForm").on('invalid-form.validate',
            function (form, validator) {
                var errors = validator.numberOfInvalids();
                if (errors) {
                    validator.errorList[0].element.focus();
                }
            }
        );
    });

How do I make fields with a regex data annotation validation attribute to get focus if it contains invalid input when the submit button is clicked?

Upvotes: 1

Views: 643

Answers (1)

Anton
Anton

Reputation: 1386

I did solve this eventually. The problem is that the error message that appears for an incorrect input shifts the position of the button. So the click is actually not hitting the button, it's hitting the background which in turn puts the focus there instead of on the incorrect input field.

This should have been avoided in the first place by using a design that doesn't reposition elements on a validation error.

Upvotes: 0

Related Questions