Jquery验证引擎:表单提交无验证

Amy*_*yth 1 jquery ajax-forms jquery-validation-engine

我正在使用Jquery验证引擎(https://github.com/posabsolute/jQuery-Validation-Engine)作为我的一个表单.验证工作正常,但即使字段值不符合验证,也无法阻止表单提交:

我有一份时事通讯Sigunp表格如下:

<form id="submit-newsletter" method="POST" action="">
   <input type="text" class="searchform validate[required, custom[email]]" value="Enter Your Email" id="email" name="nw-email" onblur="defaultInput(this);" onfocu    s="clearInput(this);" />
   <input type="hidden" id="newsletter" name="newsletter" value="nl" />
   <input type="submit" class="submit" title="Signup" value="Sign Up" name="newsletter-signup" onclick="newsletterSubscribe(event);" />
</form>
Run Code Online (Sandbox Code Playgroud)

此表单通过ajax提交如下:

// Newsletter Subscription Without Refresh

function newsletterSubscribe(e) {
  e.preventDefault();
  var dataString = 'nw-email=' + $('input[name=nw-email]').val() + '&newsletter=' + $('input[name=newsletter]').val();
  $.ajax({
    type: "POST",
    url: "/newsletter/",
    data: dataString,
    success: function () {
      $('#newsletter-box').html('<div id="message"></div>');
      $('#message').html('<img width="18px" height="18px" src="/static/img/smtick.png" /><h5>Thank You !</h5>')
      .append('<p>We have recieved your request. Please Check your mail for activation instructions. You will start recieving our newsletter once you have verified t    his email address.</p>')
      .hide()
      .fadeIn(1200);
      }
  });
  return false;
}
Run Code Online (Sandbox Code Playgroud)

验证触发器如下:

$(document).ready(function() {
  $('#submit-newsletter').validationEngine();
});
Run Code Online (Sandbox Code Playgroud)

现在我可以看到验证错误消息,但是如果我按下提交按钮,表单将被提交,而不管值是否是电子邮件地址.

有任何想法吗 ?

Jas*_*nga 10

将代码移动到单击事件处理程序并使用jquery绑定它.然后使用验证引擎验证方法测试您的表单是否有效.

$(function(){
    $('#newsletter-signup').click(function(e){
         e.preventDefault();

         //if invalid do nothing
         if(!$("#submit-newsletter").validationEngine('validate')){
         return false;
          }


      var dataString = 'nw-email=' + $('input[name=nw-email]').val() + '&newsletter=' + $('input[name=newsletter]').val();
      $.ajax({
        type: "POST",
        url: "/newsletter/",
        data: dataString,
        success: function () {
          $('#newsletter-box').html('<div id="message"></div>');
          $('#message').html('<img width="18px" height="18px" src="/static/img/smtick.png" /><h5>Thank You !</h5>')
          .append('<p>We have recieved your request. Please Check your mail for activation instructions. You will start recieving our newsletter once you have verified t    his email address.</p>')
          .hide()
          .fadeIn(1200);
          }
      });
      return false;
    })
});
Run Code Online (Sandbox Code Playgroud)