bootstrap validator动态增加验证

1,以前·没用过这个东西,为了给妹子解决问题,搜索相关博客,写了这么一个办法

<!DOCTYPE html>
<html>
<head>
    <title>BootstrapValidator demo</title>

    <link href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  <link href="http://cdn.bootcss.com/bootstrap-validator/0.5.3/css/bootstrapValidator.min.css" rel="stylesheet" />
 
  <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
  <script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script>
 
  <!-- 最新的 Bootstrap 核心 JavaScript 文件
   -->
  <script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script src="http://cdn.bootcss.com/bootstrap-validator/0.5.3/js/bootstrapValidator.min.js"></script>
</head>
<body>
    <form id="form1">
        <input type="button" value="添加" onclick="add()">
         <div class="form-group">
                <label>Username</label>
                <input type="text" class="form-control" name="username" />
            </div>
              <div class="form-group">
                 <label>aa</label>
        <select id="aa" name="AA" class="form-control" ><option value="0">请选择</option><option value="1">小明</option></select>'
          </div>
    </form>
    
    

</body>
<script type="text/javascript">
    
        $('form').bootstrapValidator({
      
             feedbackIcons: {
                        valid: 'glyphicon glyphicon-ok',
                        invalid: 'glyphicon glyphicon-remove',
                        validating: 'glyphicon glyphicon-refresh'
                       },
            fields: {
            

               username: {
                    message: '用户名验证失败',
                    validators: {
                        notEmpty: {
                            message: '用户名不能为空'
                        }
                    }
                },
               
            }
        });

        var index=1;

    function add() {
        // body..
        var html='<div class="form-group"> <label>aa'+index+'</label><select id="aa'+index+'"  class="form-control aa'+index+'" name="AA'+index+'"  ><option value="0">请选择</option><option value="1">小明</option></select></div>';
       $("form").append(html);
       
       $("form").bootstrapValidator('addField',$("#aa"+index),{
             
                validators:{
                    notEmpty:{
                        message:'学生不能为空'
                    },
                    callback: {
                      message: '必须选择一个学生',
                      callback: function(value, validator) {

                          if (value == 0) {
                              return false;
                          } else {
                              return true;
                          }

                      }
                  }
                }
            }
    );
        index++;   
    }
</script>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_41609327/article/details/81090027