vote up 5 vote down star
7

I have an MVC view with a form built with the Ajax.BeginForm() helper method, and I'm trying to validate user input with the jQuery Validation plugin. I get the plugin to highlight the inputs with invalid input data, but despite the invalid input the form is posted to the server.

How do I stop this, and make sure that the data is only posted when the form validates?

My code


The form:

<fieldset>
    <legend>leave a message</legend>
        <% using (Ajax.BeginForm("Post", new AjaxOptions
           {
               UpdateTargetId = "GBPostList",
               InsertionMode = InsertionMode.InsertBefore,
               OnSuccess = "getGbPostSuccess",
               OnFailure = "showFaliure"
           }))
           { %>
        <div class="column" style="width: 230px;">
            <p>
                <label for="Post.Header">
                    Rubrik</label>
                <%= Html.TextBox("Post.Header", null, new { @style = "width: 200px;", @class="text required" }) %></p>
            <p>
                <label for="Post.Post">
                    Meddelande</label>
                <%= Html.TextArea("Post.Post", new { @style = "width: 230px; height: 120px;" }) %></p>
        </div>
        <p>
            <input type="submit" value="OK!" /></p>
    </fieldset>


The JavaScript validation:

$(document).ready(function() {
    // for highlight
    var elements = $("input[type!='submit'], textarea, select");
    elements.focus(function() {
        $(this).parents('p').addClass('highlight');
    });
    elements.blur(function() {
        $(this).parents('p').removeClass('highlight');
    });

    // for validation
    $("form").validate();   
});
flag

3 Answers

vote up 6 vote down check

Try adding an OnBegin callback to the AjaxOptions and return the value of $('form').validate().form() from the callback. Looking at the source it appears that this should work.

function ajaxValidate() {
   return $('form').validate().form();
}

<% using (Ajax.BeginForm("Post", new AjaxOptions
       {
           UpdateTargetId = "GBPostList",
           InsertionMode = InsertionMode.InsertBefore,
           OnBegin = "ajaxValidate",
           OnSuccess = "getGbPostSuccess",
           OnFailure = "showFaliure"
       }))
       { %>

EDIT updated with correct callback name.

link|flag
OnSubmit is not one of the available options in the VS intellisense. However, when using OnBegin instead, your solution works like a charm. Thanks a great lot for the quick and correct answer! =) – Tomas Lycken Nov 18 '08 at 14:52
vote up -1 vote down

It was nice while it lasted - although you solved my problem, i immediately ran into another one...

When I try to add custom error messages and requirements to the validation, the script breaks because my input names have dots in them ("Post**.**Header", for example...). I think this could be because the options are specified in JSON strings, but I'm not sure. This naming convention is however a requirement for MVC to work, so I can't just switch it.

How do I work around this? Can I escape dots in Json, or is there another approach?

The script now looks as follows:

function ajaxValidate() {
    return $('form').validate({
        rules: {
            Post.Header: { required: true },
            PostPost: { required: true, minlength: 3 }
        },
        messages: {
            PostHeader: "Please enter a header",
            PostPost: {
                required: "Please enter a message",
                minlength: "Your message must be 3 characters long"
            }
        }
    }).form();
}
link|flag
I would appreciate if whoever just voted me down would also tell me why. I can't become better at "StackOverflow-ing" if no one tells me what I'm doing wrong... – Tomas Lycken May 15 at 23:11
3  
a wild assumption for the votedown would be that you posted your update or problem in an answer. i would suggest to delete and move it as an edit to the original question. – Konstantinos Oct 2 at 13:42
vote up -1 vote down

Never mind! After studying the details of Json i found that the dots could be included if the strings were wrapped in quotes. The working script is now

function ajaxValidate() {
    return $('form').validate({
    rules: {
        "Post.Header": { required: true },
        "Post.Post": { required: true, minlength: 3 }
    },
    messages: {
        "Post.Header": "Please enter a header",
        "Post.Post": {
            required: "Please enter a message",
            minlength: "Your message must be 3 characters long"
            }
        }
    }).form();
}

thanks for your help!

link|flag
I had a similar problem with jQuery and dots in id, so you might run into this later. Workaround was in the FAQ -- you escape with '\\'. docs.jquery.com/Frequently_Asked_Questions – eyston Nov 18 '08 at 19:12
@tomas - you ended up doing the right thing but for the wrong reason! JSON spec says you MUST use quotes because otherwise you may get reserved word issues - see stackoverflow.com/questions/380855/… – Simon_Weaver Jan 31 '09 at 6:41
In addition there is a change that may interest you in RC1. See the release notes page 14 "Form Helpers Changed to Replace Dots with Underscores When Rendering the ID Attribute". go.microsoft.com/fwlink/… – Simon_Weaver Jan 31 '09 at 6:42
I would appreciate if whoever just voted me down would also tell me why. I can't become better at "StackOverflow-ing" if no one tells me what I'm doing wrong... – Tomas Lycken May 15 at 23:11

Your Answer

Get an OpenID
or
never shown

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