【问题标题】:JQuery regex email validation preventing form from submittingJQuery正则表达式电子邮件验证阻止表单提交
【发布时间】:2017-05-03 00:35:48
【问题描述】:

我的网站上有一个“联系我们”表格,人们填写姓名、电子邮件和消息,然后点击发送。目前,如果我的代码中有电子邮件验证,表单将不会提交。

这是 HTML 表单代码:

<form role="form" id="feedbackForm">
    <div class="form-group">
        <label class="control-label" for="name">Full Name *</label>
        <div class="input-group">
            <input type="text" class="form-control" id="name" name="name" placeholder="Enter Your Name" required/>
            <span class="input-group-addon"><i class="glyphicon glyphicon-unchecked form-control-feedback"></i></span>
        </div>
        <span class="help-block" style="display: none;">Please enter your name.</span>
    </div>
    <div class="form-group">
        <label class="control-label" for="email">Email Address *</label>
        <div class="input-group">
            <input type="email" class="form-control" id="email" name="email" placeholder="Enter Your Email" required/>
            <span class="input-group-addon"><i class="glyphicon glyphicon-unchecked form-control-feedback"></i></span>
        </div>
        <span class="help-block" style="display: none;">Please enter a valid e-mail address.</span>
    </div>
    <div class="form-group">
        <label class="control-label" for="reason">Contact Reason *</label>
        <select name="reason" class="form-control" required>
            <option value="General Inquiry">General Inquiry</option>
            <option value="Schedule Appointment">Schedule Appointment</option>
            <option value="Report Issue">Report Issue</option>
            <option value="Provide Feedback">Provide Feedback</option>
        </select>
    </div>
    <div class="form-group">
        <label class="control-label" for="message">Message *</label>
        <div class="input-group">
            <textarea rows="5" class="form-control" id="message" name="message" placeholder="Enter Your Message" required></textarea>
            <span class="input-group-addon"><i class="glyphicon glyphicon-unchecked form-control-feedback"></i></span>
        </div>
        <span class="help-block" style="display: none;">Please enter a message.</span>
    </div>
    <div class="form-group">
        <div class="g-recaptcha" data-sitekey="mykey"></div>
        <span class="help-block" style="display: none;">Please check that you are not a robot.</span>
        <button type="submit" id="feedbackSubmit" class="btn btn-success btn-lg" data-loading-text="Sending..." style="display: block; margin-top: 10px;">Send Feedback
        </button>
    </div>
</form>

这是 jquery 代码:

(function () {
  //using regular expressions, validate email
  var contactFormUtils = {
    isValidEmail: function (email) {
      var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
      return regex.test(email);
    },
    //if no form errors, remove or hide error messages
    clearErrors: function () {
      $('#emailAlert').remove();
      $('#feedbackForm .help-block').hide();
      $('#feedbackForm .form-group').removeClass('has-error');
    },
    //upon form clear remove the checked class and replace with unchecked class. Also reset Google ReCaptcha
    clearForm: function () {
      $('#feedbackForm .glyphicon').removeClass('glyphicon-check').addClass('glyphicon-unchecked').css({color: ''});
      $('#feedbackForm input,textarea').val("");
      grecaptcha.reset();
    },
    //when error, show error messages and track that error exists
    addError: function ($input) {
      var parentFormGroup = $input.parents('.form-group');
      parentFormGroup.children('.help-block').show();
      parentFormGroup.addClass('has-error');
    },
    addAjaxMessage: function(msg, isError) {
      $("#feedbackSubmit").after('<div id="emailAlert" class="alert alert-' + (isError ? 'danger' : 'success') + '" style="margin-top: 5px;">' + $('<div/>').text(msg).html() + '</div>');
    }
  };

  $(document).ready(function() {

    $("#feedbackSubmit").click(function() {
      var $btn = $(this);
      $btn.button('loading');
      contactFormUtils.clearErrors();

      //do a little client-side validation -- check that each field has a value and e-mail field is in proper format
      //use bootstrap validator (https://github.com/1000hz/bootstrap-validator) if provided, otherwise a bit of custom validation
      var $form = $("#feedbackForm"),
        hasErrors = false;
      if ($form.validator) {
        hasErrors =  $form.validator('validate').hasErrors;
      } else {
        $('#feedbackForm input,#feedbackForm textarea').not('.optional').each(function() {
          var $this = $(this);
          if (($this.is(':checkbox') && !$this.is(':checked')) || !$this.val()) {
            hasErrors = true;
            contactFormUtils.addError($(this));
          }
        });
        var $email = $('#email');
        if (!contactFormUtils.isValidEmail($email.val())) {
          hasErrors = true;
          contactFormUtils.addError($email);
        }
      }
      //if there are any errors return without sending e-mail
      if (hasErrors) {
        $btn.button('reset');
        return false;
      }
      //send the feedback e-mail
      $.ajax({
        type: "POST",
        url: "php/sendmail.php",
        data: $form.serialize(),
        success: function(data) {
          contactFormUtils.addAjaxMessage(data.message, false);
          contactFormUtils.clearForm();

        },
        error: function(response) {
          contactFormUtils.addAjaxMessage(response.responseJSON.message, true);
        },
        complete: function() {
          $btn.button('reset');
        }
     });
      return false;
    });
    $('#feedbackForm input, #feedbackForm textarea').change(function () {
      var checkBox = $(this).siblings('span.input-group-addon').children('.glyphicon');
      if ($(this).val()) {
        checkBox.removeClass('glyphicon-unchecked').addClass('glyphicon-check').css({color: 'green'});
      } else {
        checkBox.removeClass('glyphicon-check').addClass('glyphicon-unchecked').css({color: ''});
      }
    });
  });
})();

当我删除验证电子邮件格式是否正确的这段代码时,表单会立即发送到我的电子邮件。

var $email = $('#email');
            if (!contactFormUtils.isValidEmail($email.val())) {
              hasErrors = true;
              contactFormUtils.addError($email);
            }

我相信这又会导致这一点:

if (hasErrors) {
        $btn.button('reset');
        return false;
      }

如果我注释掉'return false;'然后它发送表单

我找不到电子邮件验证的哪一部分阻止表单提交?

【问题讨论】:

  • 顺便说一句,我可以通过运行以下命令强制表单通过 Chrome 开发控制台提交: $.ajax({ type: "POST", url: "php/sendmail.php", data: $("#feedbackForm").serialize() });
  • 当输入的电子邮件格式不正确时,它显然会失败。这并没有错。你想达到什么目的?即使他们输入了错误的电子邮件地址,也可以发送/发布?
  • 使用我发布的代码,即使输入正确的电子邮件也会失败。
  • 您的 contactFormUtils.isValidEmail() 函数似乎是独立工作的。您是否尝试过console.log($("#email").val()) 来检查您是否正在测试您认为的价值?还是设置一个断点并单步执行?

标签: javascript jquery regex


【解决方案1】:

也许你在某处有另一个带有id="email" 的元素。

不妨试试:

$('#feedbackForm input[type=email]').each(function() {
  if (!contactFormUtils.isValidEmail(this.val())) {
    hasErrors = true;
    contactFormUtils.addError(this);
    console.log("ERROR: Invalid email: "+this.val()+" in input "+this.attr("name"));
  }
})

【讨论】:

  • 承认很尴尬,但你是对的。某处还有另一个 id="email" 。谢谢!
猜你喜欢
  • 2012-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多