9

I'm using the code below to validate (through bootstrap-validator) the content of each field in my contact form (there's also an extra check via google recaptcha). You can see and test the form at at this address.

By default, the submit button is disabled <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>, and is supposed to be re-enabled once all the fields are validated via bootstrap-validator and google recaptcha completed.

Issue: the submit button gets re-enabled directly once the first field is filled-in so there must be something somewhere that reactivates it (you can do a test by typing your name in the first field and then put your mouse over the submit button, and you will see that the button is active instead of disabled)

Any idea what the issue is and how to fix this?

Many thanks

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

    });

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

Additional script on the contact page:

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


?>
Greg
  • 3,025
  • 13
  • 58
  • 106
  • You have more issues than just that. All you have to do is complete the recaptcha to enable the submit button, regardless of whether or not you've filled in the other fields. – Nathan Arthur Aug 03 '17 at 20:52
  • Not sure if this helps, but I found that you have `novalidate="novalidate"` as an attribute in your form. Maybe this is why your submit button becomes active? – Alex Fallenstedt Aug 03 '17 at 20:59
  • Did you try renaming the submit button to something other than submit? – piisexactly3 Aug 15 '17 at 16:05
  • Hello, yes I've just did but that did not solve the issue – Greg Aug 15 '17 at 18:39

4 Answers4

2

Below is a pseudo code, kinda clone of the page that you shared, with the basic validation checks that are triggered on multiple events (keyup, change, keypress, blur).

  1. It checks if all fields are filled or not, if any one is empty, button won't be enabled.
  2. It checks if the input fields have minimum 2 characters.
  3. It checks if the message field has message length between 20 to 1000.

And in the same manner, we can keep adding custom validations to our needs.

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();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  First name<br />
  <input type="text" id="user_input" name="firstname" /><br /> Name
  <br />
  <input type="name" id="name_input" name="name" /><br /> Email<br />
  <input type="email" id="email_input" name="email" /><br />
  <br/> Your Message
  <textarea name="your_message" id="your_message"></textarea>
  <br>

  <input type="submit" id="register" value="Submit" disabled="disabled" />

</form>

Hope this helps you. Happy Coding!

Milan Chheda
  • 8,159
  • 3
  • 20
  • 35
  • Thanks for your answer. It certainly helps but would be more interested in identifying and fixing what is wrong with my current code as it is quite different than yours (it uses bootstrapvalidator ans google recaptcha). Tks anyway. – Greg Aug 05 '17 at 08:04
2

There seems to be a problem with naming the submit button submit http://bootstrapvalidator.votintsev.ru/getting-started/#name-conflict It might have caused the unexpected behavior

piisexactly3
  • 779
  • 7
  • 16
2

Just write a separated validation to your form

$("#contact_form").on('change', function () {
    $("form").each(function(){
    if ($(this).find(':input').val()== "")
    $('#submit-btn').addClass('disabled');
  });
})
HudsonPH
  • 1,838
  • 2
  • 22
  • 38
  • Thanks ! I'm away from my computer for one week but will test when i am back – Greg Aug 10 '17 at 12:12
  • you can test in a simple way if you have another computer close to you, open the page you shared and f12 -> console -> paste the code -> and test :) – HudsonPH Aug 10 '17 at 12:56
2

Actually your code is working as expected and no error in your code. But in bootstrapValidator you need to check the status of every field before success.form.bv event, like describe below.

Please add this event before .success.form.bv event like describe below.

.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) {

Let me know if it not works.

Alex Mac
  • 2,970
  • 1
  • 22
  • 39
  • Thanks ! I'm away from my computer for one week but will test when i am back – Greg Aug 10 '17 at 12:13
  • Hello Shyam, I'm just back home and have tested your solution. Seems to be working well, except 2 problems: (1) the submit button gets re-enabled once all the 4 fields are completed but before the google recaptcha validation is performed. Is there a possibility to integrate the recaptcha in the equation? and (2) if I start by completing the racaptcha, the submit button gets re-enable without filling in any of the 4 fields. Is there a way to fix this? Many thanks (ps: you can use the same link to test, it's been updated with your code) – Greg Aug 15 '17 at 14:40
  • Just tested again, and definitely a weird behavior of the submit button if you start by completing the google recaptcha and then filling-in the form fields. Could you please have a look when you get a chance? Many thanks – Greg Aug 17 '17 at 16:17