How to Make Recaptcha a Required Field

How can I make reCAPTCHA a required field?

if you want to use the native html5 popups, than here is the solution

JavaScript:

window.addEventListener('load', () => {
const $recaptcha = document.querySelector('#g-recaptcha-response');
if ($recaptcha) {
$recaptcha.setAttribute('required', 'required');
}
})

CSS:

#g-recaptcha-response {
display: block !important;
position: absolute;
margin: -78px 0 0 0 !important;
width: 302px !important;
height: 76px !important;
z-index: -999999;
opacity: 0;
}

How to make Google reCAPTCHA a required field?

What you have to do is prevent the form submission until you can validate the user response by using the Google reCaptcha verify callback, then, if it passes, allow the form to submit. See this answer: Google ReCAPTCHA how to make required? and also check the documentation: https://developers.google.com/recaptcha/docs/display#example

React-Redux : how to make ReCaptcha a required field

var Recaptcha = require('react-recaptcha');

// specifying verify callback function
var verifyCallback = function (response) {
this.setState({
reCaptchaResponse: response
});
};

ReactDOM.render(
<Recaptcha
sitekey="xxxxxxxxxxxxxxxxxxxx"
render="explicit"
verifyCallback={verifyCallback}
onloadCallback={callback}
/>,
document.getElementById('example')
);

You can pass a prop verifyCallBack to react-recaptcha, in that callback function you can store the response in state or wherever you want. Now, if response is empty you can simply disable the next button or you can put validation when user clicks on validation.

e.g. If you are storing response in state then you can check whether reCaptcha response is empty or not.

validateForm() {

// other field validations....

if (!this.state.reCaptchaResponse || this.state.reCaptchaResponse.trim().length === 0) {
return {success: false, message: 'Captcha is required.'};
}
}

Edit: For the edited question,
You can also create a state variable say btnDisabled and initialize it with true.

constructor() {
super();
this.state = {btnDisabled: true};
}

and Next button as

<button disabled={this.state.btnDisabled}>Next</button>

Now, in your validateForm method you can check whether the reCaptcha response is empty or not and based on that you can set the btnDisabled variable to true or false.

validateForm() {

// other field validations....

if (!this.state.reCaptchaResponse || this.state.reCaptchaResponse.trim().length === 0) {
return {success: false, message: 'Captcha is required.'};
} else {
this.setState({
btnDisabled: false
});
}
}

Side Note: You should never rely on client side validations. User can easily bypass client side validations. So, You should implement server side validations, too.

reCaptcha field as required

function validateForm() {     var recaptcha = document.forms["myForm"]["g-recaptcha-response"].value;    if (recaptcha == "") {        alert("Please fill reCAPTCHA");        return false;    }}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script><script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.min.js"></script><script src="https://www.google.com/recaptcha/api.js"></script>

<form name="myForm" action="login.php" onsubmit="return validateForm()" method="post"> <fieldset> <legend>Personal information:</legend> First name:<br> <input type="text" name="firstname" value="Name" required><br> Last name:<br> <input type="text" name="lastname" value="Last Name" required><br><br> <div class="g-recaptcha" data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"></div> <input type="hidden" name="recaptcha" data-rule-recaptcha="true"> <input type="submit" value="Submit"> </fieldset></form>

Set reCaptcha field as required

So I managed to make it worked. The only problem is after user completing reCaptcha, the message This field is required does not quickly dissapear. I'm using blur, keydown and focusout to detect user input and remove the error message.

JS:

$("#myForm").bind('blur keydown focusout', function(){ 

var dataArray = $("#myForm").serializeArray(),
dataObj = {};
console.dir(dataArray); //require firebug
//console.log(dataArray);

$(dataArray).each(function(i, field){
dataObj[field.name] = field.value;
});

var recaptcha = (dataObj['g-recaptcha-response']);

if(recaptcha != "") {
$( "#temp" ).remove();
}
});

$( ".register" ).click(function() {

var dataArray = $("#myForm").serializeArray(),
dataObj = {};
console.dir(dataArray); //require firebug
//console.log(dataArray);

$(dataArray).each(function(i, field){
dataObj[field.name] = field.value;
});

var recaptcha = (dataObj['g-recaptcha-response']);

$( "#temp" ).remove();

if(recaptcha == "") {
$("#recaptcha").append('<label id="temp" style="color:red;line-height:normal;font-size: small;">This field is required.</label>');
}

});

});

HTML:

<div class="g-recaptcha" name="recaptcha" id="recaptcha" data-sitekey="XXXXXXXXXXXXXXXXXXXXXXXXX"></div>   

Google ReCAPTCHA how to make required?

You have to use the reCaptcha verify response call back. Something like this: <script src='https://www.google.com/recaptcha/api.js?onload=reCaptchaCallback&render=explicit'></script>

var RC2KEY = 'sitekey',
doSubmit = false;

function reCaptchaVerify(response) {
if (response === document.querySelector('.g-recaptcha-response').value) {
doSubmit = true;
}
}

function reCaptchaExpired () {
/* do something when it expires */
}

function reCaptchaCallback () {
/* this must be in the global scope for google to get access */
grecaptcha.render('id', {
'sitekey': RC2KEY,
'callback': reCaptchaVerify,
'expired-callback': reCaptchaExpired
});
}

document.forms['form-name'].addEventListener('submit',function(e){
if (doSubmit) {
/* submit form or do something else */
}
})


Related Topics



Leave a reply



Submit