I am using reCaptcha v2 in a form for my contact page. After sending the form all the content was sent to email including the G-recaptcha-response. How can I exclude it using jquery in client - side.
This is the setup:
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<form method="post" name="frmcontact" id="frmcontact" action="/mail/contact">
<table width="100%" cellspacing="5">
<tr>
<td><div class="spancontacttitle">Full Name:</div>
<div class="spancontact">
<input type="text" class="contact" name="fullname" id="fullname" value="{{post.fullname}}" />
</div></td>
</tr>
<tr>
<td><div class="spancontacttitle">Email:</div>
<div class="spancontact relative">
<input type="text" class="contact" name="email_address" id="email_address" value="{{post.email_address}}" />
</div></td>
</tr>
<tr>
<td><span class="spancontacttitle">Your comments:</span>
<div class="spancontact"><textarea class="textareainquiry" name="comments" id="comments">{{post.comments}}</textarea></div></td>
</tr>
<tr>
<td>
<div class="g-recaptcha" data-sitekey="{{site['recaptcha-public-key']}}" data-callback="recaptchaCallback"></div>
<input type="hidden" class="hiddenRecaptcha required" name="hiddenRecaptcha" id="hiddenRecaptcha">
</td>
</tr>
<tr>
<td><input type="submit" class="submitinquiry" name="sbmt" id="sbmt" value="Send" /></td>
</tr>
</table>
</form>
<script type="text/javascript">
$(document).ready(function(){
function recaptchaCallback() {
$('#hiddenRecaptcha').valid();
};
$("#frmcontact").validate({
debug: true,
ignore: ".ignore",
submitHandler: function() {
document.frmcontact.submit(); return true;
},
rules: {
fullname: {
required: true
},
email_address: {
required: true,
email: true
},
hiddenRecaptcha: {
required: function () {
if(grecaptcha.getResponse() == '') {
return true;
} else {
return false;
}
}
}
},
messages: {
fullname: "This field must not be empty.",
email_address: "Please provide a valid email address.",
hiddenRecaptcha: "Error reCAPTCHA"
}
});
});
</script>
What I have tried is disabling the hidden input upon clicking and verifying the reCaptcha:
hiddenRecaptcha: {
required: function () {
if(grecaptcha.getResponse() == '') {
$('#hiddenRecaptcha').prop('disabled',false);
return true;
} else {
$('#hiddenRecaptcha').prop('disabled',true);
return false;
}
}
}
But, still, the form is sending the reCaptcha response. What I am missing here?
Your recaptcha will be useless without passing the g-recaptcha-response to the server for validation, so think about solving it on server side. But if you still want a client solution without changing your markup, here is possible way:
$(function() {
$("#frmcontact").submit(function(ev){
ev.preventDefault();
var arr = $(this).serializeArray();
//concole.log(arr);
//be sure that g-recaptcha-response is not there
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "/mail/contact");
$.each(arr, function(k, v) {
var newField = document.createElement("input");
newField.setAttribute("type", "hidden");
newField.setAttribute("name", v["name"]);
newField.setAttribute("value", v["value"]);
form.appendChild(newField);
});
document.body.appendChild(form);
form.submit();
});
});
The idea is to prevent original form from submitting, then to create another form invisible for user, add all required data and submit it.
This is also described here.
Related
I have a form that is being validated using jquery.validate.
I have added in reCAPTCHA 2.0 and this is being validated also.
However I want the form's submit button to be disabled untill the form is valid and this is where I am stuck.
The button is disabled but is not being enabled after the entries and captcha are all validated.
This is my form code
<div class="contact-Form">
<form id="form">
<label for="name">Name</label><br>
<input name="firstname" type="text" id="firstname" class="inputbox" value="" placeholder="Your name...">
<br><br>
<label for="name">Email</label><br>
<input name="email" type="email" id="email" class="inputbox" value="" placeholder="Your email address...">
<br><br>
<label for="name">Message</label><br>
<textarea class="messagebox" rows="10" cols="20" name="message" id="message" value="" placeholder="Your message..."></textarea>
<br><br>
<input type="hidden" class="hiddenRecaptcha required" name="hiddenRecaptcha" id="hiddenRecaptcha">
<div class="g-recaptcha" data-sitekey="6LcjETAUAAAAAPC7-qXZW4xI89k1EhUzPWnD5mAP" data-callback="recaptchaCallback"></div>
<input type="hidden" class="hiddenRecaptcha required" name="hiddenRecaptcha" id="hiddenRecaptcha">
<br><br>
<button id="submit" disabled="disabled" type="submit">Submit</button>
</form>
</div>
And my javascript
$().ready(function() {
$("#form").validate({
ignore: ".ignore",
rules: {
"firstname": {
required: true,
minlength: 3
},
"email": {
required: true,
email: true
},
"message": {
required: true
},
"hiddenRecaptcha": {
required: function() {
if(grecaptcha.getResponse() == '') {
return true;
} else {
return false;
}
}
}
},
messages: {
"firstname": {
required: "<br/> You have not entered a name!",
minlength: "<br/> Your name must consist of atleast 3 characters",
},
"email": {
required: "<br/> You have not entered an email address!",
email: "<br/> Please use a valid email address!",
},
"message": {
required: "<br/> You have not entered a message!",
}
}
});
$('#form input').on('keyup blur click', function () { // fires on every keyup & blur
if ($('#form').valid()) { // checks form for validity
$('button.btn').prop('disabled', false); // enables button
} else {
$('button.btn').prop('disabled', 'disabled'); // disables button
}
});
});
function recaptchaCallback() {
$('#hiddenRecaptcha').valid();
};
Edit
I have changed this function
$('#form input').on('keyup blur click', function () { // fires on every keyup & blur
if ($('#form').valid()) { // checks form for validity
$('button.btn').prop('disabled', false); // enables button
} else {
$('button.btn').prop('disabled', 'disabled'); // disables button
}
});
To this
$('#form input').bind('keyup blur click', function () {
if ($(this).validate().checkForm()) {
$('#submit').removeClass('button_disabled').attr('disabled', false); // enables button
} else {
$('#submit').addClass('button_disabled').attr('disabled', true); // disables button
}
});
It now enables the button when any input is valid. I want it to only enable the button when all inputs are valid.
Can someone point out where I am going wrong please I have checked other posts which is how I managed to get this working up till this point
You can try by removing the disabled attribute from your input btn
example:
$("button.btn").removeAttr("disabled");
Hope this helps you.
I have created forms using php and using jquery for validation.What i exactly need is if validation successful on submit button, disable the submit button till submission gets over.Here is my code:
if(document.location.pathname == "/contact-us"){
$("#form-contact-user").validate({
ignore: [],
rules: {
name:{
required: true
},email: {
email: true
},
phne: {
phnDash: true
},
zip: {
zipcode: true
}
},
errorPlacement: function(error, element) {
if (element.attr("type") == "checkbox") {
error.appendTo( element.parent().parent().parent(".form-checkboxes"));
}
else if (element.attr("name") == "mailing_address")
{
error.appendTo(element.parent().parent().parent());
}
else{
error.insertAfter(element);
}
}
});
Try this:
$('#btnId').attr('disabled', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" id="btnId" value="Submit">
I hope this is what you are looking for,
$('#submitBtn').click(function(event) {
//event.preventDefault();
$(this).attr('disabled', true);
//Perform Validation
//if(valid) {
// $("#form-contact-user").submit();
//}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" id="submitBtn" value="Submit">
According to the documentation you can use:
submitHandler (default: native form submit):
Callback for handling the actual submit when the form is valid.
ANSWER UPDATED
From your comment:
Getting the following error:-Uncaught TypeError: Cannot read property 'call' of undefined
This message depends on your rules. Because I don't know anything about your
html I can also assume a possible structure in the following snippet:
$("#form-contact-user").validate({
debug: true,
rules: {
name: {
required: true,
minlength: 2
},
email: {
required: true
},
phone: {
required: true
},
zip: {
required: true
}
},
errorPlacement: function (error, element) {
if (element.attr("type") == "checkbox") {
error.appendTo(element.parent().parent().parent(".form-checkboxes"));
}
else if (element.attr("name") == "mailing_address") {
error.appendTo(element.parent().parent().parent());
}
else {
error.insertAfter(element);
}
},
submitHandler: function(form) {
// do other things for a valid form
$(form).find(':submit').prop('disabled', true);
setTimeout(function() {
form.submit();
}, 1000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<form id="form-contact-user" method="get" action="">
<fieldset>
<legend>Please provide your name, email address, phone number and zipcode</legend>
<p>
<label for="name">Name (required, at least 2 characters)</label>
<input id="name" name="name" type="text">
</p>
<p>
<label for="email">E-Mail (required)</label>
<input id="email" type="email" name="email">
</p>
<p>
<label for="phone">Phone Number (required)</label>
<input id="phone" type="text" name="phone">
</p>
<p>
<label for="zip">Zip code (required)</label>
<textarea id="zip" name="zip"></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</fieldset>
</form>
I am trying to validate form fields like, Name (must not be blank), Email_id(must be valid), Mobile(Must be valid). After the filling the all info I have to send this information to server, and redirect response to different page. Here nothing is working,
my form.html
<form class="form-horizontal" id="scheduleLaterForm" name="scheduleLaterForm">
<div class="col-lg-8">
<div class="fieldgroup">
<label class="col-lg-3 control-label" for="userName">Name:<font
style="color: red;">*</font></label>
<div class="col-lg-9">
<input style=" height: 30px;" class="form-control" id="userName" name="userName"
placeholder="Full Name" value="" type="text" required>
</div>
</div>
<div class="fieldgroup">
<label for="email" class="col-lg-3 control-label">Email:<font
style="color: red;">*</font></label>
<div class="col-lg-9">
<input style="height: 30px;" class="form-control" name="email"
id="email" placeholder="you#example.com" value=""
type="text" required>
</div>
</div>
<div class="fieldgroup">
<label for="userContactNumber" class="col-lg-3 control-label">Mobile:<font
style="color: red;">*</font></label>
<div class="col-lg-9">
<input style="height: 30px; width:100%;" class="form-control" id="userContactNumber"
name="userContactNumber" placeholder="Mobile Number"
onkeypress="enableKeys(event);" maxlength="10" type="text" required>
</div>
</div>
<div class="fieldgroup">
<label class="col-lg-3 control-label"></label>
<div class="col-lg-7">
<input type="submit" value="Register" id="btnBooking" class="submit">
</div>
</div>
</div>
</form>
script for validating form and sending data
<script>
$(document).ready(function(){
$("#scheduleLaterForm").validate({
rules: {
userName: "required",
email: {
required: true,
email: true
},
userContactNumber: "required"
},
messages: {
userName: "Please enter your Name",
userContactNumber: "Please enter your Mobile number",
email: "Please enter a valid email address",
},
submitHandler: function(form) {
// get values from textboxs
var uName = $('#userName').val();
var mailId = $('#addressemailId').val();
var mobNum = $('#userContactNumber').val();
$.ajax({
url:"http://localhost/services/bookService4Homes.php",
type:"GET",
dataType:"json",
data:{type:"booking",Name:uName, Email:mailId, Mob_Num:mobNum },
//type: should be same in server code, otherwise code will not run
ContentType:"application/json",
success: function(response){
alert("success");
//alert(JSON.stringify(response));
},
error: function(err){
alert("fail");
//alert(JSON.stringify(err));
}
});
return false; // block regular submit
}
});
});
</script>
Php code
<?php
header('Access-Control-Allow-Origin: *');//Should work in Cross Domaim ajax Calling request
mysql_connect("localhost","root","root");
mysql_select_db("service4homes");
if(isset($_GET['type']))
{
if($_GET['type']=="booking"){
$name = $_GET ['Name'];
$mobile = $_GET ['Mob_Num'];
$mail = $_GET ['Email'];
$query1 = "insert into customer(cust_name, cust_mobile, cust_email) values('$name','$mobile','$mail')";
$result1=mysql_query($query1);
}
}
else{
echo "Invalid format";
}
?>
You do not need an external click handler because the plugin automatically captures the click (of a type="submit") and blocks the submit.
You need an input or button in your form that is type="submit", otherwise the plugin will not be triggered at all.
You cannot have an external .ajax function while you have form.submit within the submitHandler of your .validate() method. This means the plugin is trying to submit the form while your click handler is trying to use ajax. They both cannot work at the same time. As per docs, any ajax belongs inside the submitHandler, and it's "the right place to submit a form via Ajax after it is validated".
You don't need to check form validity because when you use the built in submitHandler, this is also done automatically.
The jQuery4U code is nothing but complicated junk; everything can be simplified greatly. It serves no useful purpose other than to cause more confusion to those seeking guidance. It comes from a popular, yet poorly explained, online demo/tutorial by Sam Deering that is linked to/from many places.
$(document).ready(function(){
$("#register-form").validate({
rules: {
userName: "required",
email: {
required: true,
email: true
},
userContactNumber: "required"
},
messages: {
userName: "Please enter your Name",
userContactNumber: "Please enter your Mobile number",
email: "Please enter a valid email address",
},
submitHandler: function(form) {
// get values from textboxs
var uName = $('#userName').val();
var mailId = $('#addressemailId').val();
var mobNum = $('#userContactNumber').val();
$.ajax({
url:"http://192.168.1.11/services/bookService4Homes.php",
type:"POST",
dataType:"json",
data:{type:"booking",Name:uName, Email:mailId, Mob_Num:mobNum },
//type: should be same in server code, otherwise code will not run
ContentType:"application/json",
success: function(response){
//alert(JSON.stringify(response));
},
error: function(err){
//alert(JSON.stringify(err));
}
});
return false; // block regular submit
}
});
});
DEMO: http://jsfiddle.net/mh6cvf2u/
Working on static pages only.. no backend is present...Hi trying to navigate between html pages, and succeesful in that. But need to switch the page only when the form is properly validate, have tried but its not working..
Need some help...
HTML:
<div class="formContainer">
<form class="form" id="loginForm">
<div class="form-group">
<label>Login</label>
</div>
<div class="form-group">
<label for="loginForm-email">Email address</label>
<input type="email" class="form-control" id="loginForm-email" name="loginForm-email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="loginForm-password">Password</label>
<input type="password" class="form-control" id="loginForm-password" name="loginForm-password" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
JS:
$(document).ready(function () {
var fnValidate = $("#loginForm").validate({
rules: {
"loginForm-email": {
required: true,
email: true
},
"loginForm-password": {
required: true,
minlength: 5
}
}
});
$('.btn').click(function(e) {
e.preventDefault();
if(fnValidate){
window.location.reload(true);
window.location.href = '../html/userPage.html';
}
else{
alert('hia');
}
});
});
The jQuery validator has custom success and failure callbacks which you can use.
As per your current approach, the fnValidate will return you an object. So you won't know whether it's validated or not. So try using the following approach.
$(document).ready(function () {
$("#loginForm").validate({
rules: {
"loginForm-email": {
required: true,
email: true
},
"loginForm-password": {
required: true,
minlength: 5
}
},
submitHandler: function () {
console.log("inside valid");
window.location.reload(true);
window.location.href = '../html/userPage.html';
// this.submit()
},
invalidHandler: function (event, validator) {
// 'this' refers to the form
console.log("Please fill the form");
}
});
});
jsfiddle example : http://jsfiddle.net/mohamedrias/2vvaN/2/
submitHandler is called only if the form is valid. So there you can submit the form.
I have a simple HTML form:
<form id="frmNewCategory">
<span>New Category Name:</span>
<input type="text" id="txtNewCategoryName">
<label>Amount:</label>
<input type="text" id="txtNewCategoryAmount">
<br>
<input type="submit" value="Create" class="importantButton button" id="btnNewCategory">
<input type="button" value="Cancel" class="button" id="btnCancelNewCategory">
</form>
And a bit of jQuery-driven JavaScript using the validation plugin that fires when btnNewCategory is clicked:
function onNewCategoryClick(event)
{
$("#frmNewCategory").validate(
{
rules:
{
txtNewCategoryName : { required: true },
txtNewCategoryAmount : { required: true, number: true }
},
messages:
{
txtNewCategoryName : { required: "*" },
txtNewCategoryAmount: { required: "*", number: "Invalid Amount." }
}
});
if (!$("#frmNewCategory").valid())
return;
event.preventDefault();
var cmd = cmdFactory.createUndoableNewCategoryCommand($(this));
cmdBus.handleCommand(cmd);
}
The method above is supposed to validate frmNewCategory. Trouble is that even if the form has invalid values or no values at all the .valid() method still returns True.
Any ideas? What am I doing wrong?
The rules take form input "names" not "ids":
<input type="text" name="txtNewCategoryName" />
<input type="text" name="txtNewCategoryAmount" />
Instead of:
<input type="text" id="txtNewCategoryName">
<input type="text" id="txtNewCategoryAmount">
Use:
<input type="text" name="txtNewCategoryName">
<input type="text" name="txtNewCategoryAmount">
This pattern worked for me before:
$(".required").filter(function () { return $(this).val() == ""; }).addClass("invalidInput");
if (this.formWrp.valid() && this.formWrp.find(".invalidInput").length == 0)
return true;
After doing so, it seems that validation is activated.