Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.Validation.Unobtrusive client side validation only works when scripts are on view page

I have an ASP.NET MVC 4 App that uses the jQuery.validation.js plugin and MVC's jQuery.validation.unobtrusive.js. I use data annotations on my view model to validate a textbox's input to be an integer.

This (nested) view is loaded within a parent view using...

<% Html.RenderPartial("New"); %>

One the first inital page load, client side validation works. But any reloading of the nested view with an ajax call, client side validation no longer works. Why is that?

Update: (Code example from webdeveloper's solution below)

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

Example:

var saveAndUpdate = function (url) {
    var myForm = $('form', $('#TheDivThatContainsTheNewHTML'));
    $.ajax({
        url: url,
        type: 'POST',
        data: myForm.serialize(),
        success: function (result) {
            $('#TheDivThatContainsTheNewHTML').html(result);
            $.validator.unobtrusive.parse($('#TheDivThatContainsTheNewHTML'));          
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
        },
        dataType: 'html'
    });
}
like image 418
duyn9uyen Avatar asked Apr 19 '13 12:04

duyn9uyen


1 Answers

But any reloading of the nested view with an ajax call, client side validation no longer works. Why is that?

Validation applies on document ready, when you refreshing page you should manually init validation for your form.

Like this:

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

Same question: jquery.validate.unobtrusive not working with dynamic injected elements

like image 128
webdeveloper Avatar answered Oct 22 '22 12:10

webdeveloper