Adding jQuery validator rules to dynamically created elements in ASP

后端 未结 3 934
面向向阳花
面向向阳花 2020-12-02 13:15

I\'ve got some dynamically inserted form fields on a page in an MVC3 project. Normally we would add the jQuery validation server-side, but in this case we can\'t (multiple

相关标签:
3条回答
  • 2020-12-02 13:54

    As it turns out, this can be done mostly in HTML by adding a few attributes to each form element:

    • A name attribute
    • data-val="true"
    • data-val-required="message"

    Like so:

    <input type='text' name="date" data-val="true" data-val-required="A date is required." />
    

    Then the form just needs to be re-parsed via JS:

    //Remove current form validation information
    $("form")
        .removeData("validator")
        .removeData("unobtrusiveValidation");
    
    //Parse the form again
    $.validator
        .unobtrusive
        .parse("form");
    
    0 讨论(0)
  • 2020-12-02 13:58

    Now that I understand what's going on with the Unobtrusive plugin side of things (which I understand is related to ASP.NET somehow), here's what you need to do:

    After you add your new element, call $.validator.unobtrusive.parseElement(newElement) and it will get added to the form. As your answer suggested, you need to set the data-val and data-val-required attributes in the new form element.

    So you end up with this:

    //create new form element
    $('form fieldset').append('<br>New Field: '+
         '<input type="text" data-val="true" data-val-required="A date is required." name="newField">'+
         ' * Also required');
    
    //add new rules to it
    $.validator.unobtrusive
      .parseElement($('form').find('input[name="newField"]').get(0));
    

    Shown here: http://jsfiddle.net/ryleyb/LNjtd/2/

    0 讨论(0)
  • 2020-12-02 14:20

    I think you had something more simple wrong - like your find('.date') wasn't actually finding anything. Because otherwise, your code looks quite reasonable to me. Here is an example of it working as you expected: http://jsfiddle.net/ryleyb/LNjtd/

    I was able to validate the code correctly with this:

    $('form fieldset')
        .append('<br>New Field: <input type="text" name="newField"> * Also required')
        .find('input[name="newField"]').rules('add', {
          required: true,
          messages: {
            required: 'New field is required'
          }
        }
    );​
    
    0 讨论(0)
提交回复
热议问题