为什么在填写所有字段之前重新启用我的提交按钮?

时间:2017-08-01 20:31:31

标签: javascript jquery bootstrapvalidator

我使用下面的代码验证(通过bootstrap-validator)我的联系表单中每个字段的内容(还有一个额外的检查通过google recaptcha)。您可以在at this address找到并测试表单。

默认情况下,提交按钮被禁用<button id="submit-btn" class="btn-upper btn-yellow btn" name="submit" type="submit" disabled><i class="fa fa-paper-plane-o" aria-hidden="true"></i> SEND</button>,并且一旦所有字段通过bootstrap-validator和google recaptcha完成验证,就应该重新启用。

问题:填写第一个字段后,会立即重新启用提交按钮,因此必须在某个地方重新激活它(您可以通过在第一个字段中输入您的名字来进行测试字段,然后将鼠标放在提交按钮上,您将看到该按钮处于活动状态而不是已禁用)

知道问题是什么以及如何解决这个问题?

非常感谢

JS:

$(document).ready(function() {

        $('#contact_form').bootstrapValidator({
            feedbackIcons: {
                valid: 'fa fa-check',
                invalid: 'fa fa-times',
                validating: 'fa fa-refresh'
            },
            fields: {
                first_name: {
                    validators: {
                            stringLength: {
                            min: 2,
                        },
                            notEmpty: {
                            message: 'aaVeuillez indiquer votre prénom'
                        }
                    }
                },
                 last_name: {
                    validators: {
                         stringLength: {
                            min: 2,
                        },
                        notEmpty: {
                            message: 'aaVeuillez indiquer votre nom'
                        }
                    }
                },
                email: {
                    validators: {
                        notEmpty: {
                            message: 'aaVeuillez indiquer votre adresse e-mail'
                        },
                        regexp: {
                        regexp: '^[^@\\s]+@([^@\\s]+\\.)+[^@\\s]+$',
                        message: 'aaVeuillez indiquer une adresse e-mail valide'
                                }
                    }
                },
                message: {
                    validators: {
                          stringLength: {
                            min: 20,
                            max: 1000,
                            message:'aaVotre message doit faire plus de 20 caractères et moins de 1000.'
                        },
                        notEmpty: {
                            message: 'aaVeuillez indiquer votre message'
                        }
                        }
                    }
                }}).on('success.form.bv', function (e) {
                e.preventDefault();
              $('button[name="submit"]').hide();

              var bv = $(this).data('bootstrapValidator');
              // Use Ajax to submit form data
              $.post($(this).attr('action'), $(this).serialize(), function (result) {
                  if (result.status == 1) {
                      $('#error_message').hide();
                      $('.g-recaptcha').hide();
                      $('#success_message').slideDown({
                          opacity: "show"
                      }, "slow");
                      $('#contact_form').data('bootstrapValidator').resetForm()
                  } else {
                        $('button[name="submit"]').show();         
                        $('#error_message').slideDown({
                          opacity: "show"
                      }, "slow")
                                    }
              }, 'json');
          }
            );

    });

提交btn:

<button id="submit-btn" class="btn-upper btn-yellow btn" name="submit" type="submit" disabled><i class="fa fa-paper-plane-o" aria-hidden="true"></i> ENVOYER</button>

联系页面上的附加脚本:

 <script type="text/javascript">
    function recaptcha_callback(){
      $('#submit-btn').removeAttr('disabled');
    }
</script> 

my sendmessage.php:

<?php

require 'PHPMailer/PHPMailerAutoload.php';

$mail = new PHPMailer;
$mail->CharSet = 'utf-8';

$email_vars = array(
    'message' => str_replace("\r\n", '<br />', $_POST['message']),
    'first_name' => $_POST['first_name'],
    'last_name' => $_POST['last_name'],
    'phone' => $_POST['phone'],
    'email' => $_POST['email'],
    'organisation' => $_POST['organisation'],
    'server' => $_SERVER['HTTP_REFERER'],
    'agent' => $_SERVER ['HTTP_USER_AGENT'],

);

// CAPTCHA


function isValid() 
{
    try {

        $url = 'https://www.google.com/recaptcha/api/siteverify';
        $data = ['secret'   => '6LtQ6_y',
                 'response' => $_POST['g-recaptcha-response'],
                 'remoteip' => $_SERVER['REMOTE_ADDR']];

        $options = [
            'http' => [
                'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                'method'  => 'POST',
                'content' => http_build_query($data) 
            ]
        ];

        $context  = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return json_decode($result)->success;
    }
    catch (Exception $e) {
        return null;
    }
}




// RE-VALIDATION (first level done via bootsrap validator js)

function died($error) {

    echo "We are very sorry, but there were error(s) found with the form you submitted. ";

    echo "These errors appear below.<br /><br />";

    echo $error."<br /><br />";

    echo "Please go back and fix these errors.<br /><br />";

    die();

}

// validation expected data exists

if(!isset($_POST['first_name']) ||

    !isset($_POST['last_name']) ||

    !isset($_POST['email']) ||

    !isset($_POST['message'])) {

    died('*** Fields not filled-in ***');       

}



//Enable SMTP debugging. 
$mail->SMTPDebug = false;                               
//Set PHPMailer to use SMTP.
$mail->isSMTP();            
//Set SMTP host name                          
$mail->Host = "smtp.sendgrid.net";
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;                          
//Provide username and password     
$mail->Username = "fdsfs";                 
$mail->Password = "@pz7HQ";                           
//If SMTP requires TLS encryption then set it
$mail->SMTPSecure = "tls";                           
//Set TCP port to connect to 
$mail->Port = 587;                                   

$mail->FromName = $_POST['first_name'] . " " . $_POST['last_name'];

//To be anti-spam compliant

/* $mail->From = $_POST['email']; */     
$mail->From = ('ghdsfds@gmail.com');
$mail->addReplyTo($_POST['email']);



$mail->addAddress("ghdsfds@outlook.com");
//CC and BCC
$mail->addCC("");
$mail->addBCC("");

$mail->isHTML(true);

$mail->Subject = "Nouveau message depuis XYZ";

$body = file_get_contents('emailtemplate.phtml');

if(isset($email_vars)){
    foreach($email_vars as $k=>$v){
        $body = str_replace('{'.strtoupper($k).'}', $v, $body);
    }
}
$mail->MsgHTML($body);


$response = array();
if(isValid()) {
    // send mail
    if(!$mail->send()) {
        $response = array('message'=>"Mailer Error: " . $mail->ErrorInfo, 'status'=> 0);
    } else {
        $response = array('message'=>"Message has been sent successfully", 'status'=> 1);
    }
} else {
    // handle error
    $response = array('message' => 'Captcha was not valid');
}


/* send content type header */
header('Content-Type: application/json');

/* send response as json */
echo json_encode($response);


?>

4 个答案:

答案 0 :(得分:2)

下面是您共享的页面的伪代码,有点克隆,以及在多个事件上触发的基本验证检查(keyupchangekeypress,{{ 1}})。

  1. 检查所有字段是否已填写,如果任何为空,则按钮无法启用。
  2. 检查输入字段是否包含最少2个字符。
  3. 检查消息字段的消息长度是否介于20到1000之间
  4. 同样,我们可以继续为我们的需求添加自定义验证

    &#13;
    &#13;
    blur
    &#13;
    required = function(fields) {
      console.clear();
      var valid = true;
      fields.each(function() { // iterate all
        var $this = $(this);
        if ((($this.is(':text') || $this.is('textarea')) && !$this.val())) {
          valid = false;
        }
    
        if ($this.is(":text") && $this.val().length < 3) {
          console.log('less than 2 characters..');
          valid = false;
        }
    
        if ($(this).attr('id') == 'your_message' && ($this.val().length < 20 || $this.val().length > 1000)) {
          console.log('aaVotre message doit faire plus de 20 caractères et moins de 1000.');
          valid = false;
        }
      });
    
      return valid;
    }
    
    validateRealTime = function() {
      var fields = $("form :input");
      fields.on('keyup change keypress blur', function() {
        if (required(fields)) {
          {
            $("#register").prop('disabled', false);
          }
        } else {
          {
            $("#register").prop('disabled', true);
          }
        }
      });
    }
    
    validateRealTime();
    &#13;
    &#13;
    &#13;

    希望这会对你有所帮助。快乐的编码!

答案 1 :(得分:2)

命名提交按钮提交时出现问题http://bootstrapvalidator.votintsev.ru/getting-started/#name-conflict这可能导致意外行为

答案 2 :(得分:2)

只需在表单中写一个单独的验证

$("#contact_form").on('change', function () {
    $("form").each(function(){
    if ($(this).find(':input').val()== "")
    $('#submit-btn').addClass('disabled');
  });
})

答案 3 :(得分:2)

实际上,您的代码按预期工作,代码中没有错误。但是在bootstrapValidator中,您需要在success.form.bv事件之前检查每个字段的状态,如下所述。

请在.success.form.bv事件之前添加此事件,如下所述。

.on('status.field.bv', function(e, data) {
    var $this = $(this);
    var formIsValid = true;
    $('.form-group', $this).each(function() {
        formIsValid = formIsValid && $(this).hasClass('has-success');
    });
    $('#submit-btn', $this).attr('disabled', !formIsValid);
}).on('success.form.bv', function(e, data) {

如果不起作用,请告诉我。