如何防止欧芹错误表单提交

时间:2018-06-05 14:47:08

标签: jquery parsley.js

基于Parsley Js documentation,当验证错误时,不清楚何时返回false。当出现表单错误时,如何防止表单提交?

 $(function () {
      $('#demo-form').parsley().on('field:validated', function() {
        var ok = $('.parsley-error').length === 0;
        $('.bs-callout-info').toggleClass('hidden', !ok);
        $('.bs-callout-warning').toggleClass('hidden', ok);
      })
      .on('form:submit', function() {
     return false; // Don't submit form for this demo
      });
    });

1 个答案:

答案 0 :(得分:1)

Preventing form submission after validation by parsley.js

$(function() {
  $('#demo-form').parsley().on('field:validated', function() {
    var ok = $('.parsley-error').length === 0;
    $('.bs-callout-info').toggle(!ok);
  });

  $("#demo-form").on('submit', function(e) {
    e.preventDefault();
    var form = $(this);

    form.parsley().validate();

    if (form.parsley().isValid()) {
      alert('valid');
    }
  });
});
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

body form {
  color: #FCFFEE;
}

#banner-message {
  float: right;
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://parsleyjs.org/dist/parsley.min.js"></script>
<form id="demo-form">
  <h2>Form</h2>
  <input type="text" required value="" />
  <button type="submit">SUBMIT</button>
</form>
<br />
<span id="banner-message" class="bs-callout-info" style="display: none">
  error
</span>

Fiddle here