Search code examples
jqueryasp.net-mvc-4jquery-post

validation fails but jQuery valid() is true and $.post executes


I am having trouble with jQuery validation and posts. I am using MVC 4 but that shouldnt matter. I have done the view source and I have all the correct HTML 5 attributes set.

Here's how I am doing a post using jQuery:

<script type="text/javascript">
    $(document).ready(function () {
        $('#btnsend').click(function (e) {
            if ($("#sendForm").validate().form()) {
                var contact = {
                    Name: $('#Name').val(),
                    Email: $('#Email').val(),
                    Message: $('#Message').val()
                };

                $.post('/Contact/Send', contact, function () {
                    $('#cSet').fadeOut(1000, "", function () {
                        $('#success').delay(1000).fadeIn(1000, "", function () {
                            $('#success').html("<h2>The message is sent. Thank you!</h2>");
                        });
                    });
                });
            }
            else {
                return false;
            }
            //return false;
        });
    });
</script>

Here's the code inside div for email textbox:

<div>
    @Html.TextBox("Email", null, new { @style = "width:400px", @Type = "email",            @placeholder="Your email" })
    @Html.ValidationMessageFor(m => m.Email)
</div>

I remove the script block everything works. With the script, email type validation doesnt work properly. I see the validator flashing but that doesnt stop the post going through.

Any help is appreciated! Thanks in advance!

Should I just use $.Ajax instead?

Here's more the validation flash occurs if the button type is submit

<div>
    <input id="btnsend" type="submit"  value="Send" />;
</div>   

If I change it to button, it does not flash or stop the post.


Solution

  • There is an issue with jquery plugin that gets shipped with MVC handling html5 input types.

    Got the latest from

    https://github.com/jzaefferer/jquery-validation/downloads

    Works like a charm!! :)

    I cant be happier. :)