Redone
Redone

Reputation: 1303

Client side validation in asp.net mvc3

I am using asp.net mvc3 for my project along with jquery ajax methods. I have been able to validate the input but if I click on the post button the data is posted even if the form contains invalid data. I know this can be solved using submit button. But I want to use my jquery methods. I have been using asp.net mvc3 client side validation. Here is my code to post the data from a form.

//jQuery
function PostForm(Url, FormID, Title) {    

    var dataTOPost = '#' + FormID; // Id of particular form to post

    $.ajax({
        url: Url,
        type: 'POST',
        data: $(dataTOPost).serialize(),
        beforeSend: function () {
            //display some loading pics
        }
    }).done(function (result) {

        //if success do something
    });

}

And I used it as follows

<a onclick="PostForm('someurl','myform', 'Title of dialog');" >Submit</a>

Here is the screen shot of part of the form being validated. Even if the form contains invalid data the form gets posted. How do I solve this. Thanks.

Certain part of form being validated

Upvotes: 0

Views: 907

Answers (2)

Cristi Pufu
Cristi Pufu

Reputation: 9095

You have to parse the form to validate using:

$.validator.unobtrusive.parse($(form));

And then ask if is valid:

$(form).valid();

Ex:

function PostForm(Url, FormID, Title) {    

        var dataTOPost = '#' + FormID; // Id of particular form to post

        $.validator.unobtrusive.parse($(dataTOPost));

        if ($(dataTOPost).valid()){

            $.ajax({
                url: Url,
                type: 'POST',
                data: $(dataTOPost).serialize(),
                beforeSend: function () {
                  //display some loading pics
                },
                done: function (result) {
                  //if success do something
                }});
        }else{
         console.log("invalid form");
        }
    }

Upvotes: 5

Joan Caron
Joan Caron

Reputation: 1970

$("a").click(function(event) {
    //cancel submit click
    event.preventDefault();
    //check errors
    ...
    //Post your form
    PostForm('someurl','myform', 'Title of dialog');
});

Upvotes: 0

Related Questions