Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7627975
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T05:31:59+00:00 2026-05-31T05:31:59+00:00

I’ve written a simple contact form in my mvc3 app. Everything seems to work

  • 0

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!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T05:31:59+00:00Added an answer on May 31, 2026 at 5:31 am

    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
    })
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am doing a simple coin flipping experiment for class that involves flipping a
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
I have a text area in my form which accepts all possible characters from
Seemingly simple, but I cannot find anything relevant on the web. What is the
I am currently running into a problem where an element is coming back from
I am writing an app with both english and french support. The app requests

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.