JQuery正则表达式电子邮件验证阻止表单提交

时间:2017-05-03 00:35:48

标签: javascript jquery regex

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

这是HTML表单代码:

<UserControl x:Class="Project.Cards.Card">
    <UserControl.Resources>
        ... perhaps something here ...
    </UserControl.Resources>
    <StackPanel>
        <TextBlock Text="{Binding Name}" />
        <TextBlock Text="{Binding Description}" />
        <TextBlock Text="{Binding Primary.Direction}" />
    </StackPanel>
</UserControl>

这里是jquery代码:

<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>

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

(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);
            }

如果我评论'return false;'然后它发送表格

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

1 个答案:

答案 0 :(得分: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"));
  }
})