Add reCAPTCHA Validation to a HTML Form | Web Development Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone and welcome to this tutorial so in this one I'm going to show you how you can add Google capture to a HTML form so this helps to validate that the submission is being made by a human user and not by a third-party script or bark and by using Google recaptchat you can make up to one million checks a month for free at the time of this recording and you get to lean on software that's well established and maintained by Google so you need a Google account set up once you have one you can go to the admin console register recapture or a new site so I'll add a reference label or test here and the recapture type I'll choose version 2 which is the one where a user has to click I'm not a robot and sometimes has two complete challenges dependent upon Google's confidence that the box has been ticked by a human user and also a manual setting where you can specify the level of security that you want to assign for the recapture now recapture will only work on domains that you specify here so when you're deploying it you'd want to include your website domain name but because I'm going to be testing this locally on my machine I'm just going to add the two domains or localhost so both point to the same resource that you're hosting locally so I'll create this recapture instance now so this provides me with two keys one for client-side validation of the recapture and one for Server site validation so I'll be showing you both of these starting with the client-side validation so if we click on the client-side integration guide you get some eulerplate code here so you can just copy in script into the head of your HTML in most browsers the async tribute means that the script will be downloaded in the background and then executed when it's available and the fur is a fallback for legacy browsers that means it will also be downloaded in the background and executed when the Dom is fully passed in both cases it means that the script is non-blocking and the second line of code from this boilerplate is a div into which the recapture will be injected so you want to place it in your form where you want recapture to appear the important bit is this class tribute for the recapture being injected here and you also need to enter your client side site key so that was the first key that we saw previously so I'll copy that in here and as an initial test so you can see how it works I'll just use the default HTML Behavior or sending the form to a live best API that mirrors in its response what you send to it so I already have this HTML being served live locally 1. 5500 using the live server extension in case you don't already have it installed you can find it and install it for free from the vs code Marketplace so if I refresh the page here the recapture appears in the form where it was positioned so let's test this first completing the capture submitting will be redirected to a page displaying what this test server received so it received the name input the message and there's also a property on there that has been automatically bound to the form which is a g capture response with a very long string response value now if I go back and try submitting the form without completing the recapture the key is there but this time with a value of an empty string so for client side recapture validation we can test the value of this property before the form is sent and if it's an empty string prevent it being sent to the server so I'll delete these attributes because these won't be necessary if the form is being submitted by HTML but I'm going to be using JavaScript now or the client-side validation and also to submit the form so in script.js I'll start by selecting the form and I'll do that bias tag name using the query selector next I'll list now for the form being submitted by adding an event listener to the form listening out for a submit event and when that occurs this Handler function will run so this event occurs when the button inside the form is clicked because it's of type submit and the first thing I want to do here is to prevent the HTML submission of the form which I can do by calling prevent default on the event object that's made available as a parameter in the Handler function now the actual validation itself so because that script was added at the top of HTML we can call the get response method on recapture and that's going to return that very long response string value that you saw in the server response and I want to query the value of that string specifically whether it's length is greater than zero so when the capture wasn't ticked it was zero in length so if it's not greater than 0 in length it wasn't ticked and I want to throw an error here that's going to prevent any more code inside this function from running so we can already test if this is working so I'll submit without completing the capture as expected that is now throwing an error if I do complete the capture no error is thrown meaning that the code subsequently will run and it's in this code that I'll submit the form using JavaScript so I'll send it to the same server as we were previously so to make a post request with fetch you pass in an options object specifying that on a method property and the body property is going to be the payload so it's going to be a value that I'll create above here with a reference of params so it should contain all of the form data so I can do that by passing in the form element in which the event is occurring so e dot Target and it's more efficient to send the form data as URL parameters because there's no file on the form so for that you can pass in the form data object that's been created into the URL search prams Constructor and the return value is going to be the URL params payload so this is the same format as it was being sent a moment ago with HTML so for the response we received back first a response object with a readable stream on it that will be in Json format for this API and we can read it to a JavaScript object by calling Json on the response object and that's going to make available in the next then method in the function the data as an object and catch any errors I'll add a catch method where I'll just log the error to console if there is one so let's test this now if the capture is not complete we get the error if it is complete we should get a response back from the server in a moment showing us the data that's been sent so we've got the name message and also a very long G capture response so this prevents a click on the submit button from submitting the form but this client-side validation can be circumvented by somebody running a script on the page that completely avoids them having to click on the button so in the code here I'm creating some params myself and then posting this to the server in the same way as I just was in the script so as you can see that worked and even if I added server-side validation here to check for the length of the response string this would still work because it's greater than zero so the way to get around this is to validate the very long string value of the response itself on the server side using a secret key which would be the server side validation key here so because it's being used on the server side unlike the client-side key it means a user on the client side doesn't have access to it and therefore doesn't have a key to do the server side validation so again I'll go to the guide for that which shows you how to construct the server-side request and what you get back as a response so for this I'm going to be using the example of a node.js Express backend that I created before this tutorial so you could use another backend language here the steps in terms of making a request and querying the response would be the same so for this node.js Express server I'm allowing a request from any endpoint and passing the body of requests with URL encoded data using the URL encoded native middleware and this data will be available as an object on direct.body on this post root which is set up on the forward slash upload endpoint and I've already started the server is up and running on Port 3000 so instead of just logging the body of the request to the console I'm going to make a request to this URL or the server side validation so working in later versions or node.js you have batch available and I can set up the request just like I did on the front end so I'll give the payload a reference of params again and I'll create the payload here again using the URL search params instructor this time passing in an object to it so the property names and values will be converted to URL parameters so the first expected parameter as a name of secret and the value is the server side key so I'll insert that and you also need to include the response key so you set that on a property of response and that's available on wreck dot body and because the property name has hyphens in it I use square bracket notation to access it it's G recapture response and you can optionally add the IP address of a user so that's easy enough it's on the request on the IP property now for the response so it comes in Json format and it has a success property that is true or false depending upon whether the validation was successful so we can query that determine how to proceed so because it's in Json we want to pass it to a JavaScript object and then we can handle the object in here if the success property is true this if block will run and if that's the case I respond to the content with a Json object that has a capture success property that is true you probably also want to include your other code here like posting the form data to the database but here I'll just stick to responding to the front end and manage the response there so if the success property on the validation object is not true then I respond to the front end with a false value and now on the front end we want to handle that so now on the front end the request it now to my own server running on Port 3000 it's still sending back Json data that I want to convert to a JavaScript object and on that object open query whether the server side validation was successful so if the value of capture success is true are logged to the console that the validation was successful otherwise a log and error to the console so I restart the server because I've made quite a few changes and let's test this now so as before if I click submit without completing the capture I get the client side validation if I submit after completing the capture as expected the validation was successful now for the case that I tried posting to the server using some of my own code so for the fetch request I'll update that because it's now to a different endpoint so if I try this validation failed because even though there's a g recapture response property with a string with a length greater than zero the code doesn't match what the recapture server was expecting in the server side validation request and because the key for doing it is on the server side that's not available for a user to attempt to do it in the browser so they can do it themselves so this is now set up with client side and server-side validation if you want more puzzles and challenges for users completing the captcha save this as a preference in the admin dashboard and then you'll get much more often some kind of puzzle or challenge when you attempt to take the capture box so that's it for this tutorial on implementing a Google recapture in a HTML form I hope you found it useful if you did please consider hitting the like button down below this video it helps with the algorithm and others to find this video and if you'd like to see more content like this from us in the future don't forget you can subscribe to the channel
Info
Channel: OpenJavaScript
Views: 35,942
Rating: undefined out of 5
Keywords:
Id: CKoCRQPfvaY
Channel Id: undefined
Length: 19min 17sec (1157 seconds)
Published: Wed Jun 28 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.