Javascript/jquery to validate the form in button click? - javascript

Hi i have a class using needs validate in form is there a way for me to validate this on button submit onclick ? or a better way to improve the coding for this ?
Where i can even call the invalid feedback ?
and also when button click it will check the valdiation first before call the database
As this code got some problem later in the end where i couldnt validate anything when button click as it passes to the database immediately without the validation check .
(function validateForm() {
'use strict';
var forms = document.getElementsByClassName('needs-validation');
Array.from(forms)
.forEach(function(form) {
form.addEventListener('submit', function(event) {
if (!form.checkValidity()) {
event.stopPropagation();
event.preventDefault();
}
form.classList.add('was-validated');
}, false)
})
})();
<form id="form" class="needs-validation" onsubmit="return validateForm()">
<!-- <label id="mandatoryField" class="hiddenfield" hidden>* is mandatory</label> -->
<div class="form-group row nameform">
<label for="validationName" class="col-form-label nameadduser">Name:</label>
<div class="col-6">
<input name="validationName" type="text" class="form-control" id="validationName" placeholder="Name" title="Name can be any. e.g. john" required>
<div class="invalid-feedback">
Enter a Name!
</div>
</div>
</div>
<div class="form-group row">
<label for="validationEmail" class="col-form-label emailadduser">Email:</label>
<div class="col-6">
<input name="validationEmail" type="email" class="form-control emails" id="validationEmail" placeholder="example1#gmail.com" pattern="^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"
required>
<div style="margin-left: 3px;" class="invalid-feedback">
Enter a correct Email format!
</div>
</div>
</div>
<div class="form-group row">
<label for="validationUserName" class="col-form-label usernameadduser">Username:</label>
<div class="col-6 ">
<input name="validationUserName" type="text" class="form-control " id="validationUserName" placeholder="Username" pattern="^(?=.{4,}$)(?:[a-zA-Z\d]+(?:[a-zA-Z\d])*)+$" title="Username should be at least 4 letter" required>
<div class="invalid-feedback">
Username must meet the following requirements:
<b>At least four letter</b>
</div>
</div>
</div>
<div class="form-group row">
<label for="validationpassword" class="col-form-label oldpasswordadduser">Old<br>
Password:</label>
<div class="col-6 d-flex">
<input name="validationpassword" type="password" class="form-control pass" id="oldpasswords" placeholder="Password" required>
<i class="bi bi-eye-slash" id="toggleoldPassword"></i>
<!-- <div style="margin-left: 15px;" class="invalid-tooltip password-empty" >
Enter a password!
</div> -->
</div>
</div>
<div class="form-group row">
<label for="validationpassword" class="col-form-label passwordadduser">Password:</label>
<div class="col-6 d-flex">
<input name="validationpassword" onChange="onChange()" type="password" class="form-control pass" id="passwords" placeholder="Password" pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##$%^&*_=+-]).{7,}$" title="Password should be like this. e.g. A123de!123"
required>
<i class="bi bi-eye-slash" id="togglePassword"></i>
<!-- <div style="margin-left: 15px;" class="invalid-tooltip password-empty" >
Enter a password!
</div> -->
<div id="passwordvalidator" class="invalid-tooltip password-notmeet">
Password must meet the following requirements:
<br><br>
<label class="color-text"> At least one capital letter</label>
<br>
<label class="color-text"> At least one special character</label>
<br>
<label class="color-text"> At least one number</label>
<br>
<label class="color-text"> Be at least 7 letter</label>
</div>
</div>
</div>
<div class="form-group row">
<label for="validationconfirmpassword" class="col-form-label passwordadduser">Re-enter<br>
Password:</label>
<div class="col-6 d-flex">
<input name="validationconfirmpassword" onChange="onChange()" type="password" class="form-control confirmpass" id="confirm_password" placeholder="Confirm Password" required>
<i class="bi bi-eye-slash" id="toggleconfirmPassword"></i>
<div style="margin-left: 20px;" class="invalid-tooltip">
Password do not match or value is null!
</div>
</div>
</div>
<div id="passwordconfirm"></div>
<div class="form-group row">
<label for="validationRole" class="col-form-label role">Role:</label>
<div class="col-3 ">
<select class="select-user-role custom-select-sm col-11" id="select-user-role" required>
<option class="selectrole" selected disabled value="">Select ....</option>
</select>
<div style="margin-left: 10px;" class="invalid-feedback">
Enter a valid user role!
</div>
</div>
</div>
<div class="form-group row placeholderimage">
<img src="" id="output" width="400" height="400" style="border-radius: 50%;" />
<input id="file-upload-input" type="file" accept="image/*" onchange="encodeImageFileAsURL(event);">
</div>
<button id="submitbtn" type="submit" class="btn-primary submitbutton" disabled>Done</button>
</form>
I have a button onclick where i got my database out when click which is this code it is with sweetalert as well not sure do we need to put the prevent button for validation here ?
$('#submitbtn').click(function() {
//get input value field
var name = $('#validationName').val();
var email = $('#validationEmail').val();
var username = $('#validationUserName').val();
var oldpassword = $('#oldpasswords').val();
var password = $('#passwords').val();
var picture = document.getElementById("output").src;
var role = $('#select-user-role').val();
//making ajax call after this retrieve
$.ajax({
url: "https://ecoexchange.dscloud.me:8090/api/postWithRawBody",
method: "POST",
contentType: "text/plain;charset=UTF-8",
headers: {
// Generally used for queries that we're planning to use
query: `UserUpdate(,'${formatParamString(name)}','${formatParamString(username)}','${formatParamString(email)}','','${formatParamString(password)}','','${formatParamString(role)}')`,
// apikey like oXkPNt3p6cuDobzBVjpsPUyawSYDFqFHVWPkijXZZstjVPLLWo
"Content-Type": "text/plain",
apikey: sessionStorage.getItem("apikey")
},
dataType: "text",
// May be quite long
// Usually an array
// Only for specific conditions
data: `UserUpdate(${getQueryInfo()["id"]},'${formatParamString(name)}','${formatParamString(username)}','${formatParamString(email)}','${formatParamString(oldpassword)}','${formatParamString(password)}','${formatParamString(picture)}','${formatParamString(role)}')`,
success: function(data, textStatus, xhr) {
// showing response from API
// showing response box that is added
//console.log(data)
$('#response').html("<div class='alert alert-success'>" + "<b>Success!</b> The information have been updated <b>successfully</b>" + "</div>")
Swal.fire({
icon: 'success',
title: 'Update Successfully!',
html: 'The information have been updated successfully!<br>By pressing <b>okay</b> this page will go to <b>view users</b> page',
showCancelButton: true,
cancelButtonText: "Cancel",
allowOutsideClick: false,
allowEscapeKey: false,
confirmButtonText: 'Okay',
cancelButtonColor: '#9b3be7', // purple
confirmButtonColor: '#79b446', // light green
heightAuto: false,
})
// footer: '<label class="fixissue">How to fix this issue?</label><br>Try to change the username input and press add button again'
.then(function(inputvalue) {
if (inputvalue.isConfirmed) {
window.location.assign('viewUsers.html?id=' + getQueryInfo()['id'])
} else if (inputvalue.isCancel) {
Swal.fire('')
}
})
},
error: function(xhr, textStatus, err) {
if (xhr["status"] == 409) {
$('#response').html("<div class='alert alert-danger'>" + "<b>Error!</b> There is an <b>duplicate</b> on username!" + "</div>")
//then
// setTimeout(function(){ window.location.reload(); },5000); //reload a page after 5 seconds
Swal.fire({
icon: 'error',
title: '<div class="color-text">Update not success!</div>',
html: 'There is an <label class="color-text"><b>duplicate</b></label> on username!<br><label class="fixissue">Solution ✔</label><br>Try to change the <b>username</b> and press <b>add</b> again',
heightAuto: false,
allowOutsideClick: false,
allowEscapeKey: false
// footer: '<label class="fixissue">How to fix this issue?</label><br>Try to change the username input and press add button again'
})
}
if (xhr["status"] == 400) {
$('#response').html("<div class='alert alert-danger'>" + "<b>Error!</b> The <b>old password </b> is incorrect!" + "</div>")
Swal.fire({
icon: 'error',
title: '<div class="color-text">Update not success!</div>',
html: 'The <label class="color-text"><b>old password</b></label> is incorrect!<br><label class="fixissue">Solution ✔</label><br>Try to change the <b>old password</b> and press <b>add</b> again',
heightAuto: false,
allowOutsideClick: false,
allowEscapeKey: false
// footer: '<label class="fixissue">How to fix this issue?</label><br>Try to change the username input and press add button again'
})
}
// if (xhr["status"] == "(failed)") {
// $('#response').html("<div class='alert alert-danger'>"+"<b>Error!</b> There is an <b>duplicate</b> on username! where you cant add in image"+"</div>")
// }
}
});
})

Related

How to prompt a sweetalert on submit button click php

enter image description hereI was working on the php laravel framework. I need to prompt a sweet alert showing the terms and conditions on clicking the submit button. I have no clue to use sweet alert. I just used some of the templates and wrote the following code. It's not working. Can anyone help me with this
#extends('layouts.app')
#section('maincontent')
<div class="login-form">
<div class="container">
<div class="row ">
<div class="innerpage-box">
#include('layouts.errors')
<div class="innerpage-box-header text-center">
<h3></b>Products to Buy</h3>
</div>
<div class="register-box-body">
<!-- <p class="login-box-msg">REGISTRATION FORM</p> -->
<form role="form" id="myForm" action="/chemOrderSave" method="Post" class="bidDetailSave">
#csrf
<input type="hidden" name="product_id" value="{{$pro[0]->id}}">
<div class="row">
<div class="col-md-6">
<label> <b> Price: </b>
{{$pro[0]->price * 1.02}}
</label> </br>
<div class="form-group">
<label for="buyer_quantity"><b> Quantity </b> <star>*</star></label>
<input type="text" class="form-control" id="buyer_quantity" name="buyer_quantity" placeholder="Enter the Quantity" value="{{$pro[0]->quantity}}">
</div>
<div class="form-group">
<label for="chem_shipping">Shipping</label>
<select name="chem_shipping" class="form-control" required>
<option value="">Please select one of the following Shipping Addresses</option>
#foreach($us as $uss)
<option value="{{$uss->id}}" > {{$uss->address}} {{$uss->city}} {{$uss->state}} {{$uss->zipcode}} {{$uss->country}} </option>
#endforeach
</select>
</div>
</div>
<button type="submit" class="btn btn-success updateOrder" ><i class="fa fa-save"></i> Submit</button>
<i class="fa fa-close"></i> Cancel
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
In the custom.js I wrote the following code
$('.container').on('click', '.updateOrder', function() {
//e.preventDefault();
var id = $(this).attr('id');
var title = "Are you sure, By Clicking accept you agree to Farmerce's user agreement and are agreeing to follow through on this transaction !";
swal({
title: title,
type:'warning',
showConfirmButton: true,
showCancelButton: true,
allowOutsideClick: false,
confirmButtonText:'Confirm',
}).then((result) => {
if (result.value) {
$.ajax({
type: 'post',
url: '/chemBuyer',
data: {'_token': $('input[name=_token]').val(), 'id':id},
success: function(data) {
if(data == 'success'){
var title= 'Successfully Order Placed!!!';
var type='success';
}else{
var title= 'Some thing went wrong with the '+name+' !!!';
var type='error';
}
swal({
title: title,
type:type,
showConfirmButton: true,
confirmButtonText:'OK',
}).then(function(){
window.location.reload();
});
}
});
}
})
});

jQuery validation for minimum and maximum length is not working with Bootstrap 4

I cannot get the jQuery plugin to validate minlength and maxlength. I cannot see the error message that the minimum length or maximum length as I specify. The contact form and the jQuery code of the contact form are as follows:
The contact form:
<form id="contactForm" class="contact-form" action="form.php" method="POST">
<div class="contact-form-success alert alert-success d-none mt-4" id="contactSuccess">
<strong>Success!</strong> Message sent!.
</div>
<div class="contact-form-error alert alert-danger d-none mt-4" id="contactError">
<strong>Error!</strong> There was an error.
<span class="mail-error-message text-1 d-block" id="mailErrorMessage"></span>
</div>
<div class="form-row">
<div class="form-group col-lg-6">
<label class="required font-weight-bold text-dark">Name</label>
<input type="text" value="" data-msg-required="Please enter your name." maxlength="100" class="form-control" name="name" id="name" required>
</div>
<div class="form-row">
<div class="form-group col">
<label class="font-weight-bold text-dark">Phone</label>
<input type="text" value="" data-msg-required="Please enter your phone number." maxlength="100" class="form-control" name="subject" id="subject" required>
</div>
</div>
<div class="form-group col-lg-6">
<label class="required font-weight-bold text-dark">Email</label>
<input type="email" value="" data-msg-required="Please enter your email address." data-msg-email="Please enter a valid email address." maxlength="100" class="form-control" name="email" id="email" required>
</div>
</div>
<div class="form-row">
<div class="form-group col">
<input type="submit" value="Send Message" class="btn btn-primary btn-modern" data-loading-text="Loading...">
</div>
</div>
</form>
<script src="js/jquery.validate.min.js"></script>
<script src="js/jquery.validate.js"></script>
<script src="js/additional-methods.js"></script>
Jquery and Javascripts links:
<script>
jQuery(function ($) {
$("#contactForm").validate({
errorClass: "error fail-alert",
validClass: "valid success-alert",
rules: {
name : {
required: true,
minlength: 3
},
phone: {
required: true,
number: true,
minlength: 8
},
email: {
required: true,
email: true
},
}
});
});
</script>
<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
Validation works, but minimum and maximum length are not working, and the error messages do not capture that; alternatively, it gives me a green tick (i.e., validated). I am not sure what is the reason for that.

On Mobile devices setTimeout() causing error

I am working on form, it is properly showing that "form is submitted" on desktop, and message hides after some seconds.
But on mobile it is not showing any message for submitted form.
Here is My code.
HTML
<p id="password_response_msgs" style="margin-left:40px; color:#F00"></p>
<div class="row">
<div class="col-sm-6 form-group">
<form name="password_form" method="post">
<label class="sr-only" for="userFirstName">Password</label>
<input type="password" class="form-control" name="password" id="user_password" placeholder="password" value="<?php echo $row['password']?>">
</div>
<div class="col-sm-6 form-group">
<label class="sr-only" for="userLastName">Confirm Password</label>
<input type="password" class="form-control" name="confirm_password" id="user_confirm_password" placeholder="Confirm Password" value="">
</div>
</div>
<div class="row">
<div class="col-md-6">
<a class="btn btn-block btn-primary" onClick="updatepassword();" style="color:#FFF">Update Password</a>
</div>
</div>
</form>
Javascript & Ajax
function updatepassword(){
var user_password = document.getElementById('user_password').value;
var user_confirm_password = document.getElementById('user_confirm_password').value;
if(user_password==''){
document.getElementById('password_response_msgs').innerHTML = 'Please Enter Password';
}else if(user_confirm_password==''){
document.getElementById('password_response_msgs').innerHTML = 'Please Enter Confirm Passowrd';
}else{
$.ajax({
url: "<?php echo BASE_URL;?>ajax/save-profile.php",
data:{command:'updatepassword',password:user_password,user_confirm_password:user_confirm_password,user_id:<?php echo $user_id;?>},
cache: false,
success: function(res) {
document.getElementById('password_response_msgs').innerHTML = res;
}
});
}
}
And i hides the message after some seconds in this way. This works on desktop, but not mobile devices. But if i delete the below code then message also shows on mobile devices.
setTimeout(function() {
$('#password_response_msgs').fadeOut('slow');
}, 10000);
why it is not working on mobile?

Validating NoCaptcha ReCaptcha

I have looked all over the internet and searched through questions here and haven't been able to find a solution to get recaptcha to validate. I am using 3 files for my form, Html file, JS file for validation(bootstrapValidator) and php file for sending mail which is with phpmailer. The form works sending the mail out and clearing the form when sumbitted. I do have the captcha inserted in the form.
What I'm trying to figure out is how to get recaptcha to work with the form properly. Right now when I hit send and no fields filled in shows errors, not on captcha. Once fields are filled in properly then errors are removed. Hit send and it will send the information to the to address. Just haven't been able to get recaptcha to work with form so when hit send and captcha is not checked then form won't be sent.
This is just one of the ways I have tried validating by putting it on my php form at the top right above date_default_timezone_set('Etc/UTC'); with no luck
if(isset($_POST['submit']) && !empty($_POST['submit'])):
     if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])):
        //your site secret key
        $secret = 'your secret key';
        //get verify response data
        $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
        $responseData = json_decode($verifyResponse);
        if($responseData->success):
Here is HTML file:
<form class="form-horizontal" action="" method="post" id="contact_form">
Set Up An Appointment
<div class="col-md-12">
<div class="allFields">* ALL FIELDS REQUIRED *</div>
</div>
<div id="mainContent" class="col-sm-12">
<!-- Full Name -->
<div class="form-group">
<label for="fullname" class="col-md-4 control-label">Full Name*</label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" placeholder="Full Name" name="fullname" class="form-control">
</div>
</div>
</div>
<!-- Address -->
<div class="form-group">
<label for="address" class="col-md-4 control-label">Address</label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-road"></i></span>
<input type="text" placeholder="Address" name="address" class="form-control">
</div>
</div>
</div>
<!-- City -->
<div class="form-group">
<label for="city" class="col-md-4 control-label">City</label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-home"></i></span>
<input type="text" placeholder="City" name="city" class="form-control">
</div>
</div>
</div>
<!-- State -->
<div class="form-group">
<label class="col-md-4 control-label">State</label>
<div class="col-md-5 selectContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-list"></i></span>
<select name="state" class="form-control selectpicker" >
<option value=" " >Please select your state</option>
<option>Ohio</option>
<option>Pennsylvania</option>
</select>
</div>
</div>
</div>
<!-- Zip Code -->
<div class="form-group">
<label for="zipcode" class="col-md-4 control-label">Zip Code</label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-globe"></i></span>
<input type="text" placeholder="Zip Code" name="zipcode" class="form-control">
</div>
</div>
</div>
<!-- Phone -->
<div class="form-group">
<label for="phone" class="col-md-4 control-label">Phone #</label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-earphone"></i></span>
<input type="text" placeholder="(330)222-2222" name="phone" class="form-control">
</div>
</div>
</div>
<!-- Email -->
<div class="form-group">
<label for="email" class="col-md-4 control-label">E-mail</label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
<input type="text" placeholder="E-mail Address" name="email" class="form-control">
</div>
</div>
</div>
<!-- Appointment Reason -->
<div class="form-group">
<label class="col-md-4 control-label">Appt Reason</label>
<div class="col-md-5 selectContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-list"></i></span>
<select name="reason" class="form-control selectpicker" >
<option value=" ">Select Your Appointment Reason</option>
<option>Roofing</option>
<option>Siding</option>
<option>Doors</option>
<option>Windows</option>
<option>Decking</option>
<option>Comfort Rooms</option>
<option>Kitchen</option>
</select>
</div>
</div>
</div>
<!-- Appointment Date -->
<div class="form-group">
<label class="col-md-4 control-label">Appt. Date</label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group date" id="datepicker">
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
<input type="text" placeholder="Date you would like Appointment" name="apptDate" class="form-control">
</div>
</div>
</div>
<!-- Appointment Time -->
<div class="form-group">
<label class="col-md-4 control-label">Appt. Time</label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group date" id="timepicker">
<span class="input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
<input type="text" placeholder="Time you would like Appointment" name="apptTime" class="form-control">
</div>
</div>
</div>
<!-- Contact Method -->
<div class="form-group">
<label class="col-md-4 control-label">Contact You</label>
<div class="col-md-5 selectContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-list"></i></span>
<select name="method" class="form-control selectpicker" >
<option value=" ">Select Your Contact Method</option>
<option>Email</option>
<option>Phone</option>
</select>
</div>
</div>
</div>
<!-- Project Description -->
<div class="form-group">
<label for="comments" class="col-md-4 control-label">Project Description</label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
<textarea name="comments" placeholder="Project Description" rows="5" class="form-control"></textarea>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Captcha</label>
<div class="col-md-5 inputGroupContainer">
<div class="g-recaptcha" data-sitekey="XXXXXXXXXXXXXXXXXXXXXXXXX"></div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-4 col-md-5" id="captchaMessage"></div>
</div>
<!-- Submit Button -->
<div class="form-group">
<div class="col-md-offset-4 col-md-5">
<button type="submit" name="submit" class="btn btn-primary">Send <span class="glyphicon glyphicon-send"></span></button>
</div>
</div>
</div> <!-- mainContent -->
</fieldset>
</form>
JS File:
$(document).ready(function() {
$('#contact_form').bootstrapValidator({
// To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
submitHandler: function(validator, form, submitButton) {
$.ajax({
type: "POST",
url: "appt.php",
data: $('#contact_form').serialize(),
success: function(){
$('#contact_form').each(function(){
this.reset();
$(contact_form).data('bootstrapValidator').resetForm();
});
},
error: function(){
alert("error");
}
});//close ajax
},
fields: {
fullname: {
validators: {
stringLength: {
min: 2,
},
notEmpty: {
message: 'Please supply your full name'
}
}
},
address: {
validators: {
stringLength: {
min: 8,
},
notEmpty: {
message: 'Please supply your street address'
}
}
},
city: {
validators: {
stringLength: {
min: 4,
},
notEmpty: {
message: 'Please supply your city'
}
}
},
state: {
validators: {
notEmpty: {
message: 'Please select your state'
}
}
},
zipcode: {
validators: {
stringLength: {
min: 5,
},
notEmpty: {
message: 'Please supply your zip code'
},
zipCode: {
country: 'US',
message: 'Please supply a vaild zip code'
}
}
},
phone: {
validators: {
notEmpty: {
message: 'Please supply your phone number'
},
phone: {
country: 'US',
message: 'Please supply a vaild phone number with area code'
}
}
},
email: {
validators: {
notEmpty: {
message: 'Please supply your email address'
},
emailAddress: {
message: 'Please supply a valid email address'
}
}
},
reason: {
validators: {
notEmpty: {
message: 'Please select what your appointment is for'
}
}
},
method: {
validators: {
notEmpty: {
message: 'Please select your preferred contact method'
}
}
},
comments: {
validators: {
stringLength: {
min: 10,
max: 200,
message:'Please enter at least 10 characters and no more than 200'
},
notEmpty: {
message: 'Please supply a description of your project'
}
}
},
}
})
});
PHP File to send:
<?php
/**
* This example shows settings to use when sending via Google's Gmail servers.
*/
//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set('Etc/UTC');
//Contact Form Data
$fullnameField = $_POST['fullname'];
$addressField = $_POST['address'];
$cityField = $_POST['city'];
$stateField = $_POST['state'];
$zipcodeField = $_POST['zipcode'];
$phoneField = $_POST['phone'];
$emailField = $_POST['email'];
$apptReasonField = $_POST['reason'];
$apptDateField = $_POST['apptDate'];
$apptTimeField = $_POST['apptTime'];
$methodField = $_POST['method'];
$commentsField = $_POST['comments'];
require 'mailer/PHPMailerAutoload.php';
//Create a new PHPMailer instance
$mail = new PHPMailer();
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 0;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = 'smtp.aol.com';
// use
// $mail->Host = gethostbyname('smtp.gmail.com');
// if your network does not support SMTP over IPv6
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "xxxxxx";
//Password to use for SMTP authentication
$mail->Password = "xxxxxxxx";
//Set who the message is to be sent from
$mail->setFrom('xxxxxxxx');
//Set who the message is to be sent to
$mail->addAddress('xxxxxxxxxx');
//Set the subject line
$mail->Subject = 'Information For Appointment Wanted';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->Body = <<<EOD
<br><p>Here is the information $fullnameField entered in your Appointment form.</p>
<br><hr><br>
<b>Name:</b> $fullnameField<hr><br>
<b>Address:</b> $addressField<hr><br>
<b>City:</b> $cityField<hr><br>
<b>State:</b> $stateField<hr><br>
<b>Zip Code:</b> $zipcodeField<hr><br>
<b>Phone #:</b> $phoneField<hr><br>
<b>E-mail:</b> $emailField<hr><br>
<b>Appointment Reason:</b> $apptReasonField<hr><br>
<b>Date Wanted For Appointment:</b> $apptDateField<hr><br>
<b>Time Wanted For Appointment:</b> $apptTimeField<hr><br>
<b>Best Way To Contact You:</b> $methodField<hr><br>
<b>Project Description:</b> $commentsField<hr><br>
EOD;
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//send the message, check for errors
if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}else{
echo "Message has been sent";
}
?>
You are essentially trying to extend your client side validation to include your reCaptcha. Since the reCaptcha isn't an input I don't believe you can extend your Bootstrap validator very easily. You can however add some additional javascript to add this validation.
You need some javascript variable to keep track of whether your reCaptcha has been solved:
var captcha_passed = false;
Tell Google's reCaptcha to call your function upon successful completion:
<div class="g-recaptcha" data-callback="on_captcha_filled" data-sitekey="XXXXXXXXXXXXXXXXXXXXXXXXX"></div>
Add another label to let your users know that this was missed. Make it hidden. The javascript will unhide it if they submit without the reCaptcha.
<div class="form-group">
<label class="col-md-4 control-label">Captcha</label>
<div class="col-md-5 inputGroupContainer">
<div class="g-recaptcha" data-callback="on_captcha_filled" data-sitekey="XXXXXXXXXXXXXXXXXXXXXXXXX"></div>
<label id="lblCaptchaRequired" hidden>Please complete the reCaptcha</label>
</div>
Add javascript function to be called by the reCaptcha:
/*
* Google reCaptcha data-callback handler.
* Sets captcha_passed to true to allow form submission and hides captcha required label.
*/
function on_captcha_filled() {
captch_passed = true;
$('#lblCaptchaRequired').hidden = true;
}
Add a check to your submit handler to verify that the reCaptcha has passed:
submitHandler: function(validator, form, submitButton) {
if (captcha_passed) {
$.ajax({
type: "POST",
url: "appt.php",
data: $('#contact_form').serialize(),
success: function(){
$('#contact_form').each(function(){
this.reset();
$(contact_form).data('bootstrapValidator').resetForm();
});
},
error: function(){
alert("error");
}
});//close ajax
}
else {
$('#lblCaptchaRequired').hidden = false;
}
},
Now when your user attempts to submit without first completing the reCaptcha they will be notified and the form will not submit.

Open modal only when form is validated

I want to open a modal dialog box only when form is completely validated with no error. At first i have disabled my button so that it should validate first and it should be enable only when form is validated. I am using jquery validation for this but does not get the result which i want. I want when user click submit button if fields are not filled it should not open modal.
here is my HTML code
<div class="form-group">
<div class="col-sm-4 col-sm-offset-2">
<button class="btn btn-white" type="reset">Cancel</button>
<!-- Trigger the modal with a button -->
<button type="button" id="myBtn" class="btn btn-primary" data-toggle="modal" data-target="#myModal" disabled />Confirm</button>
</div>
</div>
and me jquery for this
(function() {
$('#PasswordForm > input').keyup(function() {
var empty = false;
$('#PasswordForm > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#myBtn').attr('disabled', 'disabled');
} else {
$('#myBtn').removeAttr('disabled');
}
});})()
The form validation which i used is
$(document).ready(function()
{
$('#PasswordForm').formValidation({
message: 'This value is not valid',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields:
{
NPassword:
{
validators:
{
notEmpty:
{
message: 'The password is required and can\'t be empty'
}
}
},
RPassword:
{
validators:
{
notEmpty:
{
message: 'The confirm password is required and can\'t be empty'
},
identical:
{
field: 'NPassword',
message: 'The password and its confirm are not the same'
}
}
}
}
});
});
<form id="PasswordForm" method="post" class="form-horizontal" action="/HRM/HRM.PasswordChange">
<div class="hr-line-dashed"></div>
<div class="form-group">
<label class="col-sm-2 control-label">Employee Name</label>
<div class="col-sm-10">
<input type="text" disabled="" value="##UserName##" class="form-control">
</div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group">
<label class="col-sm-2 control-label">New Password</label>
<div class="col-sm-10">
<div class="row">
<div class="col-md-6">
<input type="password" name="NPassword" placeholder="New Password" class="form-control">
</div>
</div>
</div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group">
<label class="col-sm-2 control-label">Retype Password</label>
<div class="col-sm-10">
<div class="row">
<div class="col-md-6">
<input type="password" name="RPassword" placeholder="Retype Password" class="form-control">
</div>
</div>
</div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group">
<div class="col-sm-4 col-sm-offset-2">
<button class="btn btn-white" type="reset">Cancel</button>
<!-- Trigger the modal with a button -->
<button type="button" id="myBtn" class="btn btn-primary" data-toggle="modal" data-target="#myModal" disabled />Confirm</button>
</div>
</div>
</form>
any suggestion or help would be appreciated.
Try to change your button to:
<button type="button" id="myBtn" class="btn ban-primary">Confirm</button>
And add following function:
$('#myBtn').on('click', function(){
if(!empty) {
$('#myModal').modal('toggle');
}
});
You have to make empty a global variable.
(untested code)

Categories