Authentication with CAPTCHA

I have created a basic form in jsp. I am looking to make both the reCAPTCHA and the textbox mandatory fields. Currently, even if I only fill in the text box and click 'Sign In', the data is submitted. How can I enforce the reCAPTCHA to be a compulsory field?

<!DOCTYPE html>
<html lang="en">
<head>

<script src='https://www.google.com/recaptcha/api.js'></script>

</head>

<body>

<label> Form </label>

<form action = "somefile" method = "post">

  <input = "text" name = "textbox1" required>

  <div class="g-recaptcha" data-sitekey="6LdliBkTAAAAALmMlPRRm0NtKW3fz2kT2nxiWrVG"></div>

  <button type="submit" name="login">Sign In</button>

</form>

</body>
</html>

Answer №1

If you want to make the reCaptcha required using JavaScript, you can do so. Remember that you still need to verify the reCaptcha on the server side, but adding client side validation can be helpful.

  • Start by creating a JavaScript variable to keep track of the reCaptcha status:

    var captcha_passed = false;
    
  • Configure Google's reCaptcha to call a function upon successful completion:

    <div class="g-recaptcha" data-callback="on_captcha_filled" data-sitekey="6LdliBkTAAAAALmMlPRRm0NtKW3fz2kT2nxiWrVG"></div>
    
  • Include a hidden label to inform users about the missing reCaptcha. The label will be displayed if the form is submitted without completing the reCaptcha:

    <label id="lblCaptchaRequired" style="color: red" hidden>Please complete the reCaptcha</label>
    
  • Define a JavaScript function that will be triggered by the reCaptcha completion:

    function on_captcha_filled() {
        captcha_passed = true;
        document.getElementById("lblCaptchaRequired").hidden = true;
    }
    
  • Add an onsubmit handler to the form to ensure that the reCaptcha is completed before proceeding:

    <form action = "somefile" method = "post" onsubmit = "check_captcha(event)">
    
  • Implement the onsubmit handler in JavaScript:

    function check_captcha(e) {
        if (captcha_passed)
            return true;
        document.getElementById("lblCaptchaRequired").hidden = false;
        e.preventDefault();
    }
    
  • Updated form layout:

    <form action = "somefile" method = "post" onsubmit = "check_captcha(event)">
        <input = "text" name = "textbox1" required>
        <div class="g-recaptcha" data-callback="on_captcha_filled" data-sitekey="6LdliBkTAAAAALmMlPRRm0NtKW3fz2kT2nxiWrVG"></div>
        <label id="lblCaptchaRequired" style="color: red" hidden>Please complete the reCaptcha</label>
        <button type="submit" name="login">Sign In</button>
    </form>
    
  • JavaScript file:

    var captcha_passed = false;
    
    // Form onsubmit handler.
    function check_captcha(e) {
        if (captcha_passed)
            return true;
        document.getElementById("lblCaptchaRequired").hidden = false;
        e.preventDefault();
    }
    
    // Google reCaptcha data-callback handler.
    function on_captcha_filled() {
        captcha_passed = true;
        document.getElementById("lblCaptchaRequired").hidden = true;
    }
    

Upon reaching the page, the required label is hidden initially, and the captcha_passed variable is set to false. When the user submits the form, the check_captcha onsubmit handler is invoked, checking the captcha_passed status to either proceed with submission or display the label.
Once the reCaptcha is successfully completed, the on_captcha_filled function is called to update the captcha_passed status and hide the label.

Answer №2

Greetings! Below is the comprehensive solution for client-side validation:

HTML form: I have included a text box called google-response and set up three callback events: 1) data-error-callback="wrongCaptcha", 2) data-callback="correctCaptcha", 3) data-expired-callback="wrongCaptcha".

<form class="form-inline" class="text-center">
  <div class="form-group">
    <label for="email">Email:</label>
      <input type="email" id="newsletter-email" class="form-control" id="email">
  </div>
   <button type="button" class="btn btn-default" onclick="validationNewsletter()">Submit</button>
   <input type="hidden" id="google-response"/>
   <br/><br/>
  <div class="form-group">
  <div class="g-recaptcha" id="gcaptcha" data-sitekey="XXXX-XXXX" data-error-callback="wrongCaptcha" data-callback="correctCaptcha" data-expired-callback="wrongCaptcha"></div>
                </div>
</form>

JS Validation

  <script>
   function validationNewsletter() {
    if($('#google-response').val()==""||$("[name=g-recaptcha-response]").val()==""){
       alert("Please check google recaptcha");
      return false;
    }
    if($('#google-response').val()!=$("[name=g-recaptcha-response]").val()){
        alert("Sorry spammer");   
        return false;
    }
   if(letsPutFormValidation){
   alert("Some form validation");   
        return false;
  }
  $('#form-id').submit();
 }

 var correctCaptcha = function (response) {
    $('#google-response').val(response);
 };

  var wrongCaptcha=function(response){
    $('#google-response').val('');
  }
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Decomposing LocalStorage data in React using JavaScript

How can I retrieve this element from localStorage? https://i.sstatic.net/e8K3u.png Although I am able to console.log(product.priceHistory), how do I access its price element? useEffect(() => { let productFromLocalStorage = localStorage.getItem(id ...

Tips on creating a responsive absolute div

I'm currently working on creating a profile component with Material UI and React.js. I'm having trouble making the Avatar/profile photo and profile name div responsive. Here are some screenshots to illustrate my issue: The specific div that need ...

Flipping over every single card, but only desire to flip them one at a time

My attempt to flip these cards individually has resulted in them all flipping together. I suspect there may be an error in my JavaScript code. In the original code, I used images in front and an unordered list in the back, but here I have simplified it t ...

The req.isAuthenticated function in Node.js passport consistently returns false

I have encountered a problem with my authentication node.js app that I haven't been able to solve despite researching similar questions and trying various solutions. My application consists of a front end in react-native and a MongoDB database, and I ...

Blender Mesh Not Visible in Three.js

After creating a mesh in Blender, I attempted to use it in three.js. Although the file is being loaded according to the event log, all I see is a black screen. How can I ensure that the mesh actually appears on the screen? import * as THREE from 'thre ...

unable to utilize references in React

import React, { Component } from "react"; class Learning extends Component { firstName = React.createRef(); handleSubmit = event => { event.preventDefault(); console.log(this.firstName.current.value); } ...

Issues with Bootstrap 4 (possibly JQuery) - mobile menu navigation items are unresponsive

I've encountered an issue with my Bootstrap4 navbar on mobile screens where the links in the menu don't seem to work. Below is the code I used: <nav class="navbar navbar-expand-sm navbar-dark" style="background-color: #E2BA28"> < ...

Instructions for securing a React Front End with Node.js Express-Sessions authentication:

I have decided to move away from using Firestore auth in order to develop my own authentication system. Here is my goal: To create a React web app that allows users to sign up and sign in. Authenticated users should be able to interact with a REST API, w ...

Is invalid HTML causing issues with Backbone.js templating in Phonegap?

Summary: When my template file contains valid HTML code, it does not display in Phonegap. The structure of my index.html file is as follows: <body onload="onBodyLoad()"> <div data-role="page"> <a href="#login" id="clickme">C ...

How can you display varying information based on a dropdown selection using Material-UI's Select component?

By default, the Select component is populated with the correct data. However, I am facing an issue where selecting the "InReview" option should display the options inside the statusArr and remove the previous ones. Thank you in advance for your help. Her ...

Exploring ways to create fresh arrays derived from the original array

On our company website, we have a wide array of vehicles available for purchase. Among these vehicles, there is a specific group of vans with detailed information such as the model and value. {vanNumber: "7654628", vanDescription: "VW Campervan", value: { ...

"Getting an 'Undefined index' error while accessing a JavaScript variable in PHP

Every row in my table contains an Edit button. I managed to fetch the row number by clicking on the Edit button using JavaScript, but I am unsure how to do it in PHP. My attempt to pass the variable from JS to PHP resulted in an error: Undefined index ...

Retrieve JavaScript Variable Value when Button is Clicked via asp:HiddenField

Having limited experience with JavaScript and jQuery, I decided to make some modifications to a jQuery Slider for adjusting dates. You can check out what I've done so far here: http://jsfiddle.net/ryn_90/Tq7xK/6/. I managed to get the slider working ...

Building a Laravel PHP application that dynamically generates a custom JSON object fetched from the database and passes it from PHP to

I am faced with the task of generating a custom JSON object by organizing data retrieved from PHP in my Controller. I have full control over what information goes where and in what specific order. To accomplish this, it seems like I will need to go throug ...

What is the best way to apply an SVG as the background-image for this text?

After examining the fiddle, it is clear that there is code to set the background of two spans to an image created with svg. The goal now is to achieve this dynamically using javascript (either jquery or raw) on the span with the "help" class, but unfortuna ...

Is it possible to send information via the URL while using jQuery Mobile?

My mobile application utilizes an in-app browser to send information, such as deviceID, to my server via a URL. For instance, the browser opens a web-page (jquery Mobile): www.myserver.com/doWork.html#deviceID Within the doWork.html file on the server si ...

Why won't the state change when using Angular's ui-router $state.go method?

I have developed a factory that is responsible for detecting state changes and checking if a form has been modified. When the form is dirty, a modal window like a confirmation prompt should appear. However, I am encountering an issue where the $state.go() ...

The function signature '(newValue: DateRange<dateFns>) => void' does not match the expected type '(date: DateRange<unknown>, keyboardInputValue?: string | undefined) => void' as per TypeScript rules

I'm currently utilizing the MUI date range picker from https://mui.com/x/react-date-pickers/date-range-picker/. Here's my code snippet: <StaticDateRangePickerStyled displayStaticWrapperAs="desktop" value={valu ...

Ways to steer clear of using eval for converting strings to decimal values

I currently have the fraction "1/7" and I am looking to convert it into a decimal. While I know I can achieve this using eval("1/7"), I prefer not to use eval as it is considered harmful. Are there any alternative methods to accomplish this? ...

Tips for seamlessly creating the animation of sketching a line

Currently, I am working on a project that involves around 40 curved lines, each containing 30 to 200 points. Despite using BufferGeometry and setDrawRange() to draw all the lines equally, only the line with over 200 points appears smooth. I attempted using ...