提交时未显示reCaptcha错误消息

时间:2019-04-12 08:17:46

标签: jquery validation recaptcha

我正在使用jquery进行表单验证,问题是在提交recaptcha错误消息后,其他字段错误消息却无法正常工作。我要阻止表单,除非检查Recaptcha,然后表单必须提交。可能是我没有正确组合recaptcha handleError函数,我不知道我在做什么错。有人能指出我正确的方向吗?任何帮助将不胜感激

$(document).ready(function() {

  /* contact form validation */

  var Validator = function(formObject) {
    this.form = $(formObject);
    var Elements = {
      name: {
        reg: /^[a-zA-Z ]{2,20}$/,
        require: true,
        error: "Not a valid name.",
      },

      email: {
        reg: /^[a-z-0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,7}$/i,
        error: "Not a valid e-mail address.",
      },
      phone: {
        reg: /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/,
        error: "Not a valid number.",
      },

      message: {
        reg: /^(?!\s*$).+/,
        error: "Message field cannot be empty.",
      }

    };

    var handleError = function(element, message) {
      element.addClass('input-error');
      var $err_msg = element.parent('div');
      $err_msg.find('.error').remove();

      var error = $('<div class="error"></div>').text(message);
      error.appendTo($err_msg);
      console.log(element);


      element.on('keypress change', function() {
        $(error).fadeOut(1000, function() {
          console.log(element);
          element.removeClass('input-error');
        });
      });

    };

    this.validate = function() {
      var errorCount = 0;

      this.form.find("input, textarea").each(function(index, field) {
        var type = $(field).data("validation");
        var validation = Elements[type];
        if (validation !== undefined) {
          var re = new RegExp(validation.reg);
          if (validation) {
            if (!re.test($(field).val())) {
              errorCount++;
              handleError($(field), validation.error);
            }
          }
        }
      })

      return errorCount == 0;
    };
  };

  /* Submit form*/

  $(function() {

    $("#contact_form").on('submit', function(e) {
      //reCAPTCHA
       var $captcha = $( '#recaptcha' );
      var response = grecaptcha.getResponse();
      
       if (response.length === 0) {
           $('.msg-error').text( "reCAPTCHA is mandatory" );
           if( !$captcha.hasClass( "error" ) ){
               $captcha.addClass( "error" );
           }
       } else {
           $('.msg-error').text('');
           $captcha.removeClass( "error" );
       }


      var NoErrors = new Validator(this).validate();
      if (NoErrors == true) {
        $.ajax({
          url: this.action,
          type: this.method,
          data: $(this).serialize(),
          beforeSend: function(){
				   var $captcha = $( '#recaptcha' );
				   var response = grecaptcha.getResponse();
						if (response.length === 0) {
						    $('.msg-error').text( "reCAPTCHA is mandatory" );
						    if( !$captcha.hasClass( "error" ) ){
						        $captcha.addClass( "error" );
						    }
						} else {
						    $('.msg-error').text('');
						    $captcha.removeClass( "error" );
						}
				},
          success: function() {
            // AJAX request finished, handle the results and error msg
            $('.success_msg').fadeIn().delay(3000).fadeOut();
            //$('input[type=text], input[type=number], input[type=email], textarea').val('').removeClass('error');
            $('input[type!="submit"], textarea').val('').removeClass('error');
            grecaptcha.reset();
            //this.reset();
          }
        });

      }
      return false;
    })

  })
});
.success_msg {
  width: 350px;
  line-height: 40px;
  border: 1px solid green;
  border-radius: 5px;
  background-color: rgba(213, 255, 187, 0.7);
  display: none;
  bottom: 5px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 999;
  text-align: center;
}

.msg-error {
  color: red;
}

.error {
  color: red;
}

.g-recaptcha.error {
  border: solid 2px red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js"></script>
<form method="post" action="contact-form.php" id="contact_form" novalidate>
  <div class="form-row">
    <div class="col-md-12 mb-3 form-group">
      <div class="detail">
        <label>name:</label>
        <input type="text" name="name" data-validation="name" />
      </div>
      <!--detail-->
    </div>
    <div class="col-md-6 mb-3 form-group">
      <div class="detail">
        <label>Email:</label>
        <input type="email" name="email" data-validation="email" />
      </div>
      <!--detail-->
    </div>
    <div class="col-md-6 mb-3 form-group">
      <div class="detail">
        <label>phone</label>
        <input type="number" name="phone" data-validation="phone" />
      </div>
      <!--detail-->
    </div>
    <div class="form-group col-md-10 mb-3 message">
      <div class="detail message">
        <label>Message:</label>
        <textarea name="message" cols="30" rows="15" data-validation="message"></textarea>
      </div>
      <!--detail-->
    </div>
    <div class="g-recaptcha" name="reCAPTCHA" id="recaptcha" data-sitekey="6LcgSAMTAAAAACc2C7rc6HB9ZmEX4SyB0bbAJvTG" data-callback="vcc"></div>
    <div class="btn-container">
      <input type="submit" name="send" class="btn" value="Send" />
    </div>

    <div class="success_msg">
      <p>Form submitted Successfully</p>
    </div>
  </div>
</form>
<script>
  var vcc = function(g_recaptcha_response) {
    var $captcha = $('#recaptcha');

    $('.msg-error').text('');
    $captcha.removeClass("error");
  };
</script>

我曾经尝试过使用ajax beforeSend,但是在不检查Recaptcha的情况下仍然无法发送工作表格。

0 个答案:

没有答案