Check all validations with jquery before posting in asp.net mvc 5

12,898

Solution 1

Due to submitting the form via ajax you will have to manually call it.

This is one approach you could take:

$.validator.unobtrusive.parse($form);
        $form.validate();
        if ($form.valid()) {
            // ajax call
        }
        else {
          // Failed show errors
        }

If it fails the errors are contained within $form.validate().errorList but you have to manually parse them.

You can do this as follows:

    $.each($form.validate().errorList, function (key, value) {
        $errorSpan = $("span[data-valmsg-for='" + value.element.id + "']");
        $errorSpan.html("<span style='color:red'>" + value.message + "</span>");
        $errorSpan.show();
    });

This simply replaces your validation for messages manually.

Solution 2

I have solved it by including jquery.validate.unobtrusive.js in my bundles

        bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.validate*",
                    "~/Scripts/jquery.validate.unobtrusive.js"
                    ));

and check like this

  if (!$("#myform").valid()) {

           alert('not valid');

                   }
else{
// ajax logic
    }
Share:
12,898
Ghazanfar Khan
Author by

Ghazanfar Khan

Updated on June 05, 2022

Comments

  • Ghazanfar Khan
    Ghazanfar Khan almost 2 years

    I want to post my MVC form with jquery . My view model is this

     public class DemoViewModel
      {
        [Required]
        public string  FirstName { get; set; }
        [Required]
    
        public string LastName { get; set; }
      }
    

    and my controller is

      [HttpPost]
        public JsonResult LongRunningDemoProcess(DemoViewModel model)
        {
            Thread.Sleep(1000);
            return Json(model, "json");
        }
    

    and my view has the following code

    @model WebApplication2.Models.DemoViewModel
    @{
        ViewBag.Title = "Home Page";
    }
    
    
    
    @using (Html.BeginForm("LongRunningDemoProcess", "Home", FormMethod.Post,
    new { encType = "multipart/form-data", id = "myform", name = "myform" }))
    {
        <div class="form-group">
            @Html.LabelFor(model => model.FirstName,
            new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.FirstName)
                @Html.ValidationMessageFor(model => model.FirstName)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.LastName,
            new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LastName)
                @Html.ValidationMessageFor(model => model.LastName)
            </div>
        </div>
    
        <input type="submit" name="operation" id="process" value="process" />
    }
    
    <div id="divProcessing">
        <p>Processing, please wait . . . <img src="../../Content/ajax-loader.gif"></p>
    </div>
    
    <div id="divResult">
    
    </div>
    
    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
    
        <script type="text/javascript">
    
            $(document).ready(function () {
    
                // Hide the "busy" Gif at load:
                $("#divProcessing").hide();
    
                // Handle the form submit event, and make the Ajax request:
                $("#myform").on("submit", function (event) {
                    event.preventDefault();
                     // Show the "busy" Gif:
                    $("#divProcessing").show();
                    var url = $(this).attr("action");
                    var formData = $(this).serialize();
                    $.ajax({
                        url: url,
                        type: "POST",
                        data: formData,
                        dataType: "json",
                        success: function (resp) {
                            // Hide the "busy" gif:
                            $("#divProcessing").hide();
    
                            // Do something useful with the data:
                            $("<h3>" + resp.FirstName + " " + resp.LastName + "</h3>").appendTo("#divResult");
                        }
                    })
                });
            });
    
        </script>
    }
    

    but the problem is that even if their are errors of required field the form is posted and get the result

    enter image description here

    I tried to test this code if($("#myform").valid()) but there is no method available . How can I test the validation by using jquery.validate.js as it is included already. Thanks

  • Ishan
    Ishan over 3 years
    Adding reference to ~/bundles/jqueryval without unobstructive js did it for me,thanks anyways