如何在模态上显示wtform验证错误

时间:2013-12-17 14:04:48

标签: flask twitter-bootstrap-3 wtforms

我在Twitter Bootstrap 3模式中有一个WTF表单,我需要验证。问题是,即使存在验证错误,用户提交表单时模式也会关闭。如果我再次单击触发模态的按钮,则会显示验证错误。所以我的问题是,当有验证错误时,如何让模态保持打开状态? 谢谢!

<button type="button" class="btn btn-default" data-toggle="modal" role="dialog" data-target="#save"> 
<span class="glyphicon glyphicon-flash"></span>
</button>


<div class="modal fade" id="save" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
  <div class="modal-content">
   <div class="modal-header">
     <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
     <h3 class="modal-title" id="myModalLabel">Archive List and Start New</h3>
    </div>

   <form role="form_list" class="form form-medium" action="." method="post">
   {{ form_save.csrf_token }}
    <div class="modal-body">    
        <h4>Save list as: </h4>
        {{ render_field(form_save.list_name, class="input-large") }}
    </div>

    <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <a href="#">
          <button class="btn btn-success">Archive List</button></a> 
    </div>
  </form>

  </div><!-- modal content -->
  </div><!-- modal-dialog -->
</div><!-- modal -->


<script src="{{ url_for('static', filename='js/jquery.js') }}"></script>
<script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script>

1 个答案:

答案 0 :(得分:9)

如果表单中存在错误,您应该添加一些javascript来自动打开模式。

像(使用jQuery):

var formErrors = {% if form_errors %}true{% else %}false{% endif %};

$(document).ready(function() {
    if (formErrors) {
        $('.modal').modal('show');
    }
});