Google reCaptcha v2 - check captcha is completed before form submission - javascript

What is the best practice in checking a user has actually completed the captcha before form submission?
From the documentation I can see there is 2 callback functions data-callback and data-expired-callback.
The plan is to manipulate a boolean javascript variable setting to true/false on successful completion or on expiration and then check that the variable is true before form submission.
From a user perspective this will ensure that the user fills out the captcha before submission.
Malicious users could overwrite the javascript variable but the server side captcha validation will protect against this.

First in your form you have to put onsubmit="return check()". That means when you're submiting the form, before sending datas it will execute the function named check(). If the function returns false the form won't submit. It will look like this :
<form action="page.php" method="POST" name="form" onsubmit="return checkCaptcha ()">
Then you have your function :
<script language="javascript">
function checkCaptcha ()
{
var captcha = document.getElementById('captcha ').value;
if (captcha == "" || captcha == " ")
{
alert("please fill the captcha ");
return false;
}
else
if (captcha .length != 7)
{
return false
} // and so on
else
{
// if everything is ok you can submit
return true;
}
}
</script>

Related

Covering all the bases with Form Validation, Client/Server - What is best way?

I know there are many methods of validating forms on both client and server side but I was wondering what was the best practice?
Currently, I have Javascript functions validating form input fields 'on the fly' with onkeyup/onblur functions like so:
(Partial code:)
<p class="form-registerUserName">
<div class="upperLabel">
<label for="registerUserName">User Name</label>
<span class="required">*</span>
</div>
<input
id="registerUserName"
name="registerUserName"
type="text"
size="24"
maxlength="24"
value="<?php echo $_SESSION['registerUserName'];?>"
onkeyup="validateName()"
onblur="checkDuplicateName(); validateName()"
>
<label for="registerUserName" class="hint" id="registerUserNameHint"></label>
</p>
With Javascript functions like:
function validateName() {
userName = document.getElementById("registerUserName").value.trim();
re = /^[a-zA-Z0-9_]{1,30}$/;
if (userName==="") {
document.getElementById('registerUserName').style.borderColor="red";
document.getElementById('registerUserNameHint').innerHTML = 'required';
} else if (!re.test(userName)) {
document.getElementById('registerUserName').style.borderColor="red";
document.getElementById('registerUserNameHint').innerHTML = 'only alphanumeric characters and _';
} else {
document.getElementById("registerUserName").setAttribute("style","border-color: rgb(221,221,221) rgb(241,241,241) rgb(241,241,241) rgb(221,221,221);");
document.getElementById('registerUserNameHint').innerHTML = '';
}
} //validateName()
..So that the input box turns red and shows a hint on the side of the box if it does not validate.
So my question was - What is the best way to prevent the form from submission to my (Mysqli) database when the user hits submit?
(and second question..) Do I run an additional php server-side script after client-side validation has cleared?
Some ways I imagined to accomplish this is by having my Javascript functions set a Session variable that indicates an error condition, and not allow a submit if there was.
I am not certain how to do that, or how I set up my 'submit' to not work unless the error condition was cleared.
Would appreciate any help on that.
Then do I re-validate the same data (in the same manner) with php again, after a successful client-side validation before inserting into my database?
Thanks in advance.
First off, always do server-side validation!
Second, HTML5 form validation is well supported.
Examples: http://html5pattern.com/
You can then use CSS for validation styling.
Structure your validation with this logic:
if validateName() {
document.getElementById("myForm").submit();
}
// if returns true (passed validation) then submit
//validate on click of submit button or on submit
function validateName() {
userName = document.getElementById("registerUserName").value.trim();
re = /^[a-zA-Z0-9_]{1,30}$/;
if (userName==="") {
document.getElementById('registerUserName').style.borderColor="red";
document.getElementById('registerUserNameHint').innerHTML = 'required';
**return false;**
} else if (!re.test(userName)) {
document.getElementById('registerUserName').style.borderColor="red";
document.getElementById('registerUserNameHint').innerHTML = 'only alphanumeric characters and _';
**return false;**
........ so forth
else {
return true;
}

Empty Form Submission Javascript

I'm trying to stop people from sending me blank emails through my contact us on my website. On my main website I have succeeded with the following javascript:
<script type="text/javascript">
function checkForm(f)
{
if (f.elements['cf_name'].value == "" && f.elements['cf_email'].value == "" && f.elements['cf_message'].value == "")
{
alert("You have not filled in all of the required fields.");
return false;
}
else
{
f.submit();
return false;
}
}
</script>
Although this works, when I implemented the same on my mobile website, people are still able to send blank emails.
The HTML code I used for the form check is:
<form action="contact.php" method="post" name="sform" onSubmit="return checkForm(this);">
So my question is how do i stop form submission if the fields are empty, on a mobile device (specifically iPhone)
Are you sure this isn't a logic error? Seems like this:
if (f.elements['cf_name'].value == "" && f.elements['cf_email'].value == "" && f.elements['cf_message'].value == "")
Should be:
if (f.elements['cf_name'].value == "" || f.elements['cf_email'].value == "" || f.elements['cf_message'].value == "")
Although client-side validation is useful because it's more immediate, you should never rely on it, and using Javascript alone to do this sort of check is riddled with holes (as you found). Write code which will work nicely if Javascript works, and will still do the validation you want if Javascript is not implemented.
Since you are sending your form data to a php script, do your checking there as well as in the client and only send the mail if the form data is valid.

Running a script if form field validates as email

Sorry for this most likely simple question.
I am running a script on submission of the form (code below), but first I would like to validate the form (contains one text box which must be an email) before the code is executed.
The script below is taken from here to ensure the form data is passed along to the colorbox lightbox script. But i only want to run this if the form is validated. I don't know how to combine this with an email validation script. Help! At the moment i've got a script that validates email (dreamweaver's) and this running, this command still runs even if it doesn't validate and i am not sure how to edit it so it doesn't.
$(document).ready(function() {
$("input#SearchButton").colorbox({href: function(){
var url = $(this).parents('form').attr('action');
var ser = $(this).parents('form').serialize(); //alert(url+'?'+ser);
return url+'?'+ser;
}, innerWidth:"1280", innerHeight:"884px", iframe:true, scrolling:false});
});
Then I am using this to validate the form:
function MM_validateForm() { //v4.0
if (document.getElementById){
var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
if (val) { nm=val.name; if ((val=val.value)!="") {
if (test.indexOf('isEmail')!=-1) { p=val.indexOf('#');
if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
} else if (test!='R') { num = parseFloat(val);
if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
min=test.substring(8,p); max=test.substring(p+1);
if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
} }} else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
} if (errors) alert('The following error(s) occurred:\n'+errors);
document.MM_returnValue = (errors == '');
} }
Thanks!!!!
The HTML for the tigger is:
<input name="submit" type="image" onclick="MM_validateForm('email','','RisEmail');return document.MM_returnValue" src="images/go-button.gif" alt="Go! Get quote now!" align="top" : id="SearchButton"/>
In a nutshell: I want to tigger the code in the first snippet if the form validates using the code in the second snippet that is called by the html even in the third code snippet, but not if it doesn't.
You didn't post your HTML so I don't know if you have an actual form or just an input field without an actual form tag.
Assuming the former, you need a submit event so you can validate the form and then, if validation failed, terminate the submission.
$('#my_form').submit(function() {
//validate - forget the whole thing if it fails
if (!$('#my_field').val()) return false;
//if we get this far, validation succeeded - do other stuff now
});
A form submission is halted any time the submit callback returns false (or fires event.preventDefault()).
Andrew is correct, it would help if you provided the html in order to establish what the event trigger will be. Having reviewed the jquery plugin 'colorbox' briefly, it appears the lightbox is bound to the selectors click event.
Assuming Andrew's answer, if the email address validates you would need to manually trigger the click event for the lightbox from within the submit handler for the form. The following code should suffice.
$('#my_form').on('submit', function(e){
//perform validation.
MM_validateForm('email','','RisEmail');
//check the document variable set by the validation.
if (!document.MM_returnValue)
{
//did not validate
}else{
//open the colorbox
var search_btn = $('input#search');
search_btn.colorbox({href: function(){
var url = $(this).parents('form').attr('action');
var ser = $(this).parents('form').serialize();
return url + '?' + ser;
},
innerWidth: "1280",
innerHeight: "884px",
iframe:true,
scrolling:false});
//manually trigger the click event
search_btn.trigger('click');
}
//in either instance, disable the default action to ensure the form does not follow through.
e.preventDefault();
});
Obviously you'll have to replace the css selector names with your own, and utilise the email validation script that you may or may not have.

help with if statement - min of 3 characters

Since there is no minlength="" for input, how can I make an if statement that does the following:
If the user has not input more than 3 characters it will not be saved in a database.
Here is the input:
QTY<input title="QUANTITY PER ITEM" size="1" name="inputQTY" value="**(minimun of 3 characters)**"/>
any ideas??
Note: it doesn't matter if there's a min value restriction on the input field or not; a user can still spoof the form to contain whatever value he or she wants. Thus, you need to validate on the server side.
Let's say you're using PHP as your server side language.
$inputQTY = $_POST['inputQTY'];
if (strlen($inputQTY) < 3) {
// DO NOT INSERT INTO DB
}
else {
// insert after further scrubbing input
}
Read this: What's the best method for sanitizing user input with PHP?
Form validation is the process of checking if the form fields are filled in correct formats if they are processes. In your question, the correct format is "more than 3 characters". Of course, if statements are involved during form validations. In the client-side, you use JavaScript code to validate form fields.
Here is how it works: A form has an onsubmit event handler, when the user clicks Submit, or presses Enter, onsubmit will be triggered. onsubmit is where you put the form validation code.
<script>
function onsubmit() {
if (document.forms.mainForm.inputQTY.value.length < 3) {
alert("ERROR: Must be more than 3 characters");
return false; // stops the form submission
}
return true;
}
</script>
And here is how you add the onsubmit handler
...
The onsubmit function can return a value: true to let the form to be submitted, or false to stop the submission.
What is document.forms.mainForm.inputQTY.value.length? document.forms.mainForm references to the form named mainForm, while .inputQTY finds the inputQTY field.
You can use document.getElementsByTagName to manually find these elements, but it is [time and space]-consuming to write that type of code.
Because some users have JavaScript disabled, or crackers intentionally disable JS to bypass validation, you must validate server-side.
Server-side code will be something like this:
if (strlen($_GET['inputQTY']) < 3) {
echo "ERROR: Must be more than 3 characters";
} else {
// submit data
}
NOTE: code written from head, not tested

onunload - Check if Form was submitted

I have a form on a webpage.when the user moves from that page, I want to check that the form was submitted. If it was, then the user simply continues to the next page, if not, the user receives an alert msg and is brought back to the original page where the form resides.
I am not too familiar with javascript so I would appreciate some code snippets if that's possible?
GF
Your question is a bit vague. Your question implies that you're submitting the form asynchronously, but you said that you aren't familiar with JavaScript. Submitting a form asynchronously requires JS knowledge. Also, if you're actually submitting the form synchronously, the solution would have been too obvious (just render some JS conditionally on the server side).
If you're actually submitting the form asynchronously, then just set some token/toggle in as form's data-xxx attribute after the succesful form submit. E.g.
function submit(form) {
// Do your thing to submit it.
// And then on succes:
form['data-submitted'] = true;
return false;
}
Then, during beforeunload event you just check if the token/toggle is there and in case it's missing, return the message accordingly.
window.onbeforeunload = function() {
for (var i = 0; i < document.forms.length; i++) {
var form = document.forms[i];
if (form['data-submitted'] != 'undefined' && !form['data-submitted']) {
return "There is unsaved data!";
}
}
}
Note that you can't use unload event for this since it too late then to keep the page open.
Update: so the form is submitted synchronously. Okay, whatever server side language you're using, just let it conditionally render a JS window.onbeforeunload call when the form is not submitted (you obviously already know when the form is been submitted, how else would you be able to process it? ;) ). You also need to disable the window.onbeforeunload call when the form is about to be submitted.
Based on your question history I bet that you know PHP, so here's a PHP targeted kickoff example:
<?php
if (!$form_is_submitted) {
echo '<script>window.onbeforeunload = function() { return "There is unsaved data!"; }</script>';
echo '<form onsubmit="window.onbeforeunload=null">';
}
?>

Categories