Validate a form in MVC 4 using JQuery while using Jquery Ajax post

8159
Views
1
Answers

How to validate a entire form in MVC 4 using jQuery? I need to submit the form using Jquery Ajax post after validating. The validation dosent occur and the form gets posted without ajax .
here is my razor view

@using (Html.BeginForm("", "", FormMethod.Post, new {id = "myForm"}))
{

       
@Html.LabelFor(m => m.UserName)
       
@Html.TextBoxFor(m => m.UserName)
       
@Html.ValidationMessageFor(m => m.UserName)



       
@Html.LabelFor(m => m.Password)
       
@Html.TextBoxFor(m => m.Password)
       
@Html.ValidationMessageFor(m => m.Password)



       
@Html.LabelFor(m => m.EmailAddress)
       
@Html.TextBoxFor(m => m.EmailAddress)
       
@Html.ValidationMessageFor(m => m.EmailAddress)



   input type
="submit" id="submitForm" value="Submit" />
}

and the Javascript:

     $(function () {
       $
("#myForm").submit(function (e) {
        $
('#myForm').validate();
                        e
.preventDefault();
                   
});
       
});
but the validation
is not showing up..
edit | flag
Mad Maddy
Asked on: Jan 28, 2012 at 7:21AM

1 Answers

108
9
108

Just use the code below to prevent default submission and to validate on clicking submit button.

 $("#myForm").submit(function (e) {

                e
.preventDefault();
           
});
            $
("input#submitForm").click(function () {
               
if ($('#myForm').valid()) {
                    $
.ajax({
                        type
: "POST",
                        url
: "/controller/action",
                        data
: $("#myForm").serialize(),
                        success
: function (result) {
                           alert
('sucess');
                       
}
                   
});

               
} return false;
           
});

and dont forget to include the validation scripts

src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript">
src
="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript">
edit | flag
Askamoeba Member
Answered on: Jan 28, 2012 at 7:34AM

Post your Answer

Search

Welcome to Ask Amoeba!
This is 100% free and interactive site for sharing professional Questions and Answers, Opensource projects, Interview questions.
Learners, beginners, Experts stop and share your knowledge and ideas!

Browse Categories

Browse Tags