104

I'm having problems trying to get the unobtrusive jquery validation to work with a partial view that is loaded dynamically through an AJAX call.

I've been spending days trying to get this code to work with no luck.

Here's the View:

@model MvcApplication2.Models.test

@using (Html.BeginForm())
{
 @Html.ValidationSummary(true);
 <div id="res"></div>
 <input id="submit" type="submit" value="submit" />
}

The Partial View:

@model MvcApplication2.Models.test

@Html.TextAreaFor(m => m.MyProperty);
@Html.ValidationMessageFor(m => m.MyProperty);

<script type="text/javascript" >
  $.validator.unobtrusive.parse(document);
</script>

The Model:

  public class test
  {
    [Required(ErrorMessage= "required field")]
    public int MyProperty { get; set; }
  }

The Controller:

    public ActionResult GetView()
    {
        return PartialView("Test");
    }

and finally, the javascript:

$(doument).ready(function () {
$.ajax({
    url: '/test/getview',
    success: function (res) {

        $("#res").html(res);
        $.validator.unobtrusive.parse($("#res"));
    }
});

$("#submit").click(function () {
    if ($("form").valid()) {
        alert('valid');
        return true;
    } else {
        alert('not valid');
        return false;
    }
});

The validation does not work. Even if I don't fill any information in the texbox, the submit event shows the alert ('valid').

However, if instead of loading dynamically the view, I use @Html.Partial("test", Model) to render the partial View in the main View (and I don't do the AJAX call), then the validation works just fine.

This is probably because if I load the content dynamically, the controls don't exist in the DOM yet. But I do a call to $.validator.unobtrusive.parse($("#res")); which should be enough to let the validator about the newly loaded controls...

Can anyone help ?

DLeh
  • 23,806
  • 16
  • 84
  • 128
Sam
  • 13,934
  • 26
  • 108
  • 194
  • 2
    Note, the `unobtrusive.parse` function takes a selector as an argument, not an element. – Fred Apr 12 '16 at 13:17
  • I had also the same problem, but in mvc 2. I go through the step by step as : http://weblogs.asp.net/imranbaloch/archive/2010/07/11/asp-net-mvc-client-side-validation-with-dynamic-contents.aspx This might also help you. http://weblogs.asp.net/imranbaloch/archive/2011/03/05/unobtrusive-client-side-validation-with-dynamic-contents-in-asp-net-mvc.aspx Hope this help :) – Naresh Parmar Jun 03 '13 at 09:38

8 Answers8

247

If you try to parse a form that is already parsed it won't update

What you could do when you add dynamic element to the form is either

  1. You could remove the form's validation and re validate it like this:

    var form = $(formSelector)
        .removeData("validator") /* added by the raw jquery.validate plugin */
        .removeData("unobtrusiveValidation");  /* added by the jquery unobtrusive plugin*/
    
    $.validator.unobtrusive.parse(form);
    
  2. Access the form's unobtrusiveValidation data using the jquery data method:

    $(form).data('unobtrusiveValidation')
    

    then access the rules collection and add the new elements attributes (which is somewhat complicated).

You can also check out this article on Applying unobtrusive jquery validation to dynamic content in ASP.Net MVC for a plugin used for adding dynamic elements to a form. This plugin uses the 2nd solution.

KyleMit
  • 30,350
  • 66
  • 462
  • 664
Nadeem Khedr
  • 5,273
  • 3
  • 30
  • 37
  • I was afraid that I should invite it by myself. Script from that page works like a charm. – cezarypiatek Nov 28 '14 at 11:11
  • Code, works great - quick update (if I may) 1. I'm using knockout and getting the names of the fields well it looks like a problem so. $.validator.unobtrusive.parseDynamicContent('form'); (to get all the fields), at the end when submitting. 2. This is nice https://johnnyreilly.github.io/jQuery.Validation.Unobtrusive.Native/AdvancedDemo/Knockout.html to give you a way to name the fields (which seems to be required? I'm using jquery unbtrusive bootstrap ontop of the other 2 so my circumstances are probably different) – Richard Housham Jul 19 '16 at 15:11
  • Just a note that any form specific settings you have applied to `$("form").data("validator").settings` will be removed by `$(formSelector).removeData("validator")` and replaced with the defaults from `$.validator.defaults` when reparsing the form. This is a great way to include dynamic fields, but make sure to repeat any custom initialization code on each fresh parse. – KyleMit Apr 24 '17 at 14:37
  • Using solution 1) causes form and form elements to have duplicated event listeners (like onKeypUp) if you try to reset it and parse it multiple times (like in my case where it's dynamic content added/removed via JS). Any tips to unbind all events and avoid this repetition? on jquery.validate 1.10, newer versions have a destroy method – AlfaTeK Nov 16 '20 at 05:27
20

As an addition to Nadeem Khedr's answer....

If you've loaded a form in to your DOM dynamically and then call

jQuery.validator.unobtrusive.parse(form); 

(with the extra bits mentioned) and are then going to submit that form using ajax remember to call

$(form).valid()

which returns true or false (and runs the actual validation) before you submit your form.

Mark Jerzykowski
  • 812
  • 8
  • 15
  • hi, im facing the same issue. im showing my dynamic view in a pop up (jquery dialog). the unobstrusive validations are not working. where do I call $(form).valid() in my dynamic view or some where else? – mmssaann Jul 18 '13 at 07:54
  • I was always preventing the form from submitting by returning false inside $(form).submit because I was doing an AJAX submit, but then I needed a way to not call the AJAX submit when validation failed. $(form).valid() is the answer! Thank you! – jgerman Apr 10 '18 at 16:45
7

Surprisingly, when I viewed this question, the official ASP.NET docs still did not have any info about the unobtrusive parse() method or how to use it with dynamic content. I took the liberty of creating an issue at the docs repo (referencing @Nadeem's original answer) and submitting a pull request to fix it. This information is now visible in the client side validation section of the model validation topic.

Rabadash8820
  • 2,328
  • 3
  • 27
  • 49
6

add this to your _Layout.cshtml

 $(function () {
        //parsing the unobtrusive attributes when we get content via ajax
        $(document).ajaxComplete(function () {
            $.validator.unobtrusive.parse(document);
        });
    });
Djobs
  • 77
  • 1
  • 3
4

test this:

if ($.validator.unobtrusive != undefined) {
    $.validator.unobtrusive.parse("form");
}
Omid.Hanjani
  • 1,444
  • 2
  • 20
  • 29
4

I got struck in the same problem and nothing worked except this:

$(document).ready(function () { 
    rebindvalidators();
});

function rebindvalidators() {
    var $form = $("#id-of-form");
    $form.unbind();
    $form.data("validator", null);
    $.validator.unobtrusive.parse($form);
    $form.validate($form.data("unobtrusiveValidation").options);
}

and add

// Check if the form is valid
var $form = $(this.form);
if (!$form.valid())
    return;

where you are trying to save the form.

I was saving the form through Ajax call.

Hope this will help someone.

Jay
  • 1,037
  • 5
  • 23
  • 41
0

just copy this code again in end of modal code

    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

;)

0

For me, this worked

resetUnobtrusiveValidation: function (form) {
    form.removeData('validator');
    form.removeData('unobtrusiveValidation');
    $.validator.unobtrusive.parse(form);
}
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129