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 = ('[email protected]');
$mail->addReplyTo($_POST['email']);
$mail->addAddress("[email protected]");
//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);
?>
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.
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
).
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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With