3

I am trying to parse a dynamically inserted form to add the jQuery unobtrusive validation.

I have the following AJAX function which is executed when the user is searching:

function search(el)
{
    var $this = $(el);
    var $form = $this.closest("form");
    var url = $form.attr("action");
    $results = $("#pnlSearchResults");

    $.ajax({
        type: "POST",
        url: url,
        data: $form.serialize()
    })
    .done(function(data){
        $results.html('');
        $results.html(data);

        var $editForm = $results.find("form.edit-form");
        $editForm.removeData("validator");
        $editForm.removeData("unobtrusiveValidation");
        $.validator.unobtrusive.parse($editForm);
    });
}

This inserts an editable form for the returned entity into a <div> on the page which looks like this. I have two fields which are required, but when I remove the values from those fields the "Required" validation does not fire. It only seems to occur when:

  1. I delete the values.
  2. Take the cursor away from the field.
  3. Enter a new value.
  4. Take the cursor away.
  5. Then delete the new value.

How can I solve this so that the validation occurs when I delete the value the first time?

97ldave
  • 5,249
  • 4
  • 25
  • 39

1 Answers1

0

I found this question, which led me to an answer on this page.

(function ($) {
  $.validator.unobtrusive.parseDynamicContent = function (selector) {
    //use the normal unobstrusive.parse method
    $.validator.unobtrusive.parse(selector);

    //get the relevant form
    var form = $(selector).first().closest('form');

    //get the collections of unobstrusive validators, and jquery validators
    //and compare the two
    var unobtrusiveValidation = form.data('unobtrusiveValidation');
    var validator = form.validate();

    $.each(unobtrusiveValidation.options.rules, function (elname, elrules) {
      if (validator.settings.rules[elname] == undefined) {
        var args = {};
        $.extend(args, elrules);
        args.messages = unobtrusiveValidation.options.messages[elname];
        //edit:use quoted strings for the name selector
        $("[name='" + elname + "']").rules("add", args);
      } else {
        $.each(elrules, function (rulename, data) {
          if (validator.settings.rules[elname][rulename] == undefined) {
            var args = {};
            args[rulename] = data;
            args.messages = unobtrusiveValidation.options.messages[elname][rulename];
            //edit:use quoted strings for the name selector
            $("[name='" + elname + "']").rules("add", args);
          }
        });
      }
    });
  }
})($);

Usage:

var html = "<input data-val='true' "+
           "data-val-required='This field is required' " +
           "name='inputFieldName' id='inputFieldId' type='text'/>";
$("form").append(html);

$.validator.unobtrusive.parseDynamicContent('form input:last');
Community
  • 1
  • 1
DLeh
  • 23,806
  • 16
  • 84
  • 128