sterix24
sterix24

Reputation: 2400

How can I stop the textbox focus when my form is invalid?

I've written a simple contact form in my mvc3 app. Everything seems to work perfectly except there seems to be a problem with the focus being placed on my email field on an invalid submission, despite ALL fields being invalid. Here is the ViewModel I'm using:

public class ContactViewModel
{
    [Required(ErrorMessage="Please enter your name")]
    public string Name { get; set; }

    [Required(ErrorMessage="Please enter your email address")]
    [RegularExpression(@"^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$", ErrorMessage="Please enter a valid email address")]
    public string Email { get; set; }

    [Required(ErrorMessage="Please enter your message")]
    public string Message { get; set; }     
}

As you can see, the only difference between the fields is I have an extra regex validator in the Email field. I figure this has something to do with why it jumps to this particular field on failed validation?

Here is the code for my view:

@model  MSExport.Models.ContactViewModel
@{
    ViewBag.Title = "Contact";
}
@section HeaderScripts
{
    <script type="text/javascript">
        $(document).ready(function () {
            $('INPUT.auto-hint, TEXTAREA.auto-hint').focus(function () {
                if ($(this).val() == $(this).attr('title')) {
                    $(this).val('');
                    $(this).removeClass('auto-hint');
                }
                else { $(this).removeClass('auto-hint'); }
            });
            $('INPUT.auto-hint, TEXTAREA.auto-hint').blur(function () {
                if ($(this).val() == '' && $(this).attr('title') != '') {
                    $(this).val($(this).attr('title'));
                    $(this).addClass('auto-hint');
                }
            });

            IterateFields();

            $('form').submit(function () {
                AmendValues();
                if ($(this).valid()) {
                    var contactVM = {
                        Name: $('#Name').val(),
                        Email: $('#Email').val(),
                        Message: $('#Message').val()
                    };

                    $('form').slideUp('slow', function () {
                        $('#result').html("<img src='/images/loading.gif' alt='Loading' />");
                        $.ajax({
                            url: '/Contact/SubmitForm',
                            type: "POST",
                            data: JSON.stringify(contactVM),
                            contentType: "application/json; charset=utf-8",
                            success: function (result) {
                                $('#result').empty();
                                $('#result').html(result);
                            },
                            error: function () {
                                $('#result').empty();
                                $('#result').html("<p>There was a problem submitting your message. Please try again.</p>");
                            }
                        });
                    });
                }
                else {
                    IterateFields();
                    // TODO: Stop focus going to email field
                }                
            });
        });

        function AmendValues() {
            $('#contact-form-wrapper INPUT[type=text],TEXTAREA').each(function () {
                if ($(this).val() == $(this).attr('title')) { $(this).val(''); }
            });
        }

        function IterateFields() {
            $('INPUT.auto-hint, TEXTAREA.auto-hint').each(function () {
                if ($(this).attr('title') == '') { return; }
                if ($(this).val() == '') { $(this).val($(this).attr('title')); }
                else { $(this).removeClass('auto-hint'); }
            });
        }
    </script>
}

<h1>Contact</h1>
<div id="result"></div>
@using (Html.BeginForm()) { 
    <div id="contact-form-wrapper">
        <label for="Name">
            @Html.TextBoxFor(model => model.Name, new { @class = "auto-hint", @title = "Name", @tabindex = "1", @maxlength = "100" }) 
            @Html.ValidationMessageFor(model => model.Name) 
        </label>
        <label for="Email">
            @Html.TextBoxFor(model => model.Email, new { @class = "auto-hint", @title = "Email", @tabindex = "2", @maxlength = "200" }) 
            @Html.ValidationMessageFor(model => model.Email) 
        </label>
        <label for="Message">
            @Html.TextAreaFor(model => model.Message, new { @class = "auto-hint", @title = "Message", @tabindex = "3", @maxlength = "2000" })
            @Html.ValidationMessageFor(model => model.Message) 
        </label> 
        <input type="submit" value="Submit" tabindex="4" id="submit" />         
    </div> 
}

I tried shifting the focus to the submit button by putting $('#submit').focus() where the // TODO: comment is. However this didn't fix the problem as it still seemed to shift the focus to the Email field BEFORE shifting it to the submit button, which in turn meant my 'auto-hint' for this field got removed.

Is there any way I can stop the focus from being shifted at all? And if not, can I somehow shift it to the submit button without it first going to my Email field?

Thanks!

Upvotes: 0

Views: 596

Answers (1)

Greg
Greg

Reputation: 31378

Could this be of use to you?

http://docs.jquery.com/Plugins/Validation/Reference#Focusing_of_invalid_elements

To implement the options follow these docs (under the options tab)

http://docs.jquery.com/Plugins/Validation/validate#options

e.g.

$(".selector").validate({
   focusInvalid: false
})

Upvotes: 2

Related Questions