验证动态添加的输入字段

时间:2012-07-18 07:25:41

标签: javascript jquery html jquery-validate

我使用了this jquery验证插件,用于以下格式。

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>

<script>
    $(document).ready(function(){
        $("#commentForm").validate();
    });

    function addInput() {
        var obj = document.getElementById("list").cloneNode(true);
        document.getElementById('parent').appendChild(obj);
    }
</script>

<form id="commentForm" method="get" action="">
    <p id="parent">
        <input id="list"  class="required" />
    </p>

    <input class="submit" type="submit" value="Submit"/>
    <input type="button" value="add" onClick="addInput()" />
</form>

单击添加按钮时,会动态添加新输入。但是,在提交表单时,只验证第一个输入字段。如何验证动态添加的输入? 谢谢......

10 个答案:

答案 0 :(得分:37)

添加新字段后重置表单验证。

function resetFormValidator(formId) {
    $(formId).removeData('validator');
    $(formId).removeData('unobtrusiveValidation');
    $.validator.unobtrusive.parse(formId);
}

答案 1 :(得分:33)

您的输入应该有'name'属性。您需要动态添加规则,一个选项是在表单提交时添加它们。

这是我已经测试过的解决方案,并且可行:

<script type="text/javascript">
   $(document).ready(function() {
        var numberIncr = 1; // used to increment the name for the inputs

        function addInput() {
            $('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));
            numberIncr++;
        }

        $('form.commentForm').on('submit', function(event) {

            // adding rules for inputs with class 'comment'
            $('input.comment').each(function() {
                $(this).rules("add", 
                    {
                        required: true
                    })
            });            

            // prevent default submit action         
            event.preventDefault();

            // test if form is valid 
            if($('form.commentForm').validate().form()) {
                console.log("validates");
            } else {
                console.log("does not validate");
            }
        })

        // set handler for addInput button click
        $("#addInput").on('click', addInput);

        // initialize the validator
        $('form.commentForm').validate();

   });


</script>

html表单部分:

<form class="commentForm" method="get" action="">
    <div>

        <p id="inputs">    
            <input class="comment" name="name0" />
        </p>

    <input class="submit" type="submit" value="Submit" />
    <input type="button" value="add" id="addInput" />

    </div>
</form>
祝你好运!如果它适合你,请批准答案!

答案 2 :(得分:4)

发布的mahesh无效,因为缺少属性名称:

所以而不是

<input id="list" class="required"  />

您可以使用:

<input id="list" name="list" class="required"  />

Modified version

答案 3 :(得分:2)

jquery验证插件版本可以在 v1.15.0 上正常运行,但是 v1.17.0 对我不起作用。

$(document).find('#add_patient_form').validate({
          ignore: [],
          rules:{
            'email[]':
            {
              required:true,
            },               
          },
          messages:{
            'email[]':
            {
              'required':'Required'
            },            
          },    
        });

答案 4 :(得分:1)

您需要在添加动态内容后重新解析表单以验证内容

  <Grid>
    <Grid.Background>
        <ImageBrush ImageSource="/EasyRun2.0;component/Resources/Images/gradientWallpaper.jpg"/>
    </Grid.Background>
    <TextBlock Text="{Binding WelcomeMessage}" HorizontalAlignment="Center" VerticalAlignment="Center" FontWeight="Bold" Margin="428,128,99.6,228"/>
    <StackPanel Orientation="Vertical" VerticalAlignment="Bottom" Margin="0,0,0,20">
    </StackPanel>
    <TabControl TabStripPlacement="Left" Margin="0,0,-0.4,0" Background="{x:Null}">
        <TabItem Header="&#xF0A7;"  Height="80" FontSize="50" Background="{x:Null}" >
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                <Border x:Name="Border1" BorderBrush="Gainsboro" BorderThickness="5" CornerRadius="8,8,3,3" Margin="10,10,168.8,10.4" >
                    <ListBox x:Name="lbButtons" Background="{x:Null}" BorderBrush="{x:Null}" Margin="10,10,10,10" Loaded="lbButtons_Loaded"/>
                </Border>
                <Border x:Name="Border2" BorderBrush="Gainsboro" BorderThickness="5" CornerRadius="8,8,3,3" Grid.ColumnSpan="2" Margin="263,10,9.2,10" />
            </Grid>
        </TabItem>
        <TabItem Header="&#xF0F7;"  Height="80"  FontSize="50">
            <TabItem.Background>
                <ImageBrush/>
            </TabItem.Background>
        </TabItem>
        <TabItem Header="&#xF013;"  Height="80" FontSize="50" Background="{x:Null}" >
            <Button x:Name="ButtonAdd" Content="+" Tag="ADD" Background="{x:Null}" Click="Button_Click"/>
        </TabItem>

    </TabControl>
</Grid>

答案 5 :(得分:1)

关于@RitchieD响应,这里有一个jQuery插件版本,如果你使用jQuery,可以更容易。

(function ($) {

    $.fn.initValidation = function () {

        $(this).removeData("validator");
        $(this).removeData("unobtrusiveValidation");
        $.validator.unobtrusive.parse(this);

        return this;
    };

}(jQuery));

可以这样使用:

$("#SomeForm").initValidation();

答案 6 :(得分:0)

尝试使用输入数组:

<form action="try.php" method="post">
    <div id="events_wrapper">
        <div id="sub_events">
            <input type="text" name="firstname[]" />                                       
        </div>
    </div>
    <input type="button" id="add_another_event" name="add_another_event" value="Add Another" />
    <input type="submit" name="submit" value="submit" />
</form>

并添加此脚本和jQuery,使用foreach()检索$ _POST'的数据:

<script>                                                                                    
    $(document).ready(function(){
        $("#add_another_event").click(function(){
        var $address = $('#sub_events');
        var num = $('.clonedAddress').length; // there are 5 children inside each address so the prevCloned address * 5 + original
        var newNum = num + 1;
        var newElem = $address.clone().attr('id', 'address' + newNum).addClass('clonedAddress');

        //set all div id's and the input id's
        newElem.children('div').each (function (i) {
            this.id = 'input' + (newNum*5 + i);
        });

        newElem.find('input').each (function () {
            this.id = this.id + newNum;
            this.name = this.name + newNum;
        });

        if (num > 0) {
            $('.clonedAddress:last').after(newElem);
        } else {
            $address.after(newElem);
        }

        $('#btnDel').removeAttr('disabled');
        });

        $("#remove").click(function(){

        });

    });
</script>

答案 7 :(得分:0)

如果您有表格,可以添加类名:

<form id="my-form">
  <input class="js-input" type="text" name="samplename" />
  <input class="js-input" type="text" name="samplename" />
  <input class="submit" type="submit" value="Submit" />
</form>

然后您可以使用验证器的addClassRules方法添加这样的规则,这将适用于所有动态添加的输入:

$(document).ready(function() {
  $.validator.addClassRules('js-input', {
    required: true,
  });
  //validate the form
  $('#my-form').validate();
});

答案 8 :(得分:0)

int x = 0;

foreach (string file in optimizelist)
{
    for (int i = 0; i < Filelist.Count; i++)
    {
        if (Path.GetFileName(file) == Path.GetFileName(Filelist[i]))
        {
            Filelist.RemoveAt(x);
            Filelist.Add(file);

            break;
        }
     }

     x++;
}

答案 9 :(得分:0)

$('#form-btn').click(function () {
//set global rules & messages array to use in validator
   var rules = {};
   var messages = {};
//get input, select, textarea of form
   $('#formId').find('input, select, textarea').each(function () {
      var name = $(this).attr('name');
      rules[name] = {};
      messages[name] = {};

      rules[name] = {required: true}; // set required true against every name
//apply more rules, you can also apply custom rules & messages
      if (name === "email") {
         rules[name].email = true;
         //messages[name].email = "Please provide valid email";
      }
      else if(name==='url'){
        rules[name].required = false; // url filed is not required
//add other rules & messages
      }
   });
//submit form and use above created global rules & messages array
   $('#formId').submit(function (e) {
            e.preventDefault();
        }).validate({
            rules: rules,
            messages: messages,
            submitHandler: function (form) {
            console.log("validation success");
            }
        });
});