how do I get Javascript to recognise an email address? - javascript

I am trying to give a textfield a dual function. So, if you type, say, 12345, into it, it finds the relevant data. But if you type an email-address, or essentially anything with an XXX#XXX.XXX format, I want the password-field and button to appear. I've been trying to use regex, but for some reason it does not work, and everything is recognised as an email, so even 12345 opens the login-things. Can you help me? I've tried getting the gist into the snippets.
function imgMain() {
var iDCode = document.getElementById("IDQuery").value;
var mail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
if (iDCode = mail) {
console.log("this is a mail");
document.getElementById("passwordDiv").style.display = "block";
document.getElementById("loginbuttonDiv").style.display = "block";
document.getElementById("SeeSlide").style.display = "none";
} else {
console.log("this is not a mail")
}
}
<div id="QueryField">
<input type="text" id="IDQuery" placeholder="ID Kode">
<div style="display: none" id=passwordDiv><input type="password" id="passwordfield"><br></div>
<div style="display: none" id=loginbuttonDiv><button id="login" onclick="login()">log ind</button><br></div>
<button id="SeeSlide" onclick="imgMain()">Se Slide</button><br>
<br><br><br><br>
</div>

user mail.test() with proper regex like so
let mail = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(mail.test(iDCode)){
alert("Valid email is required")
}

You can try this version, it's based on the w3resource.
function imgMain() {
var iDCode = document.getElementById("IDQuery").value;
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (iDCode.match(mailformat)) {
console.log("this is a mail");
document.getElementById("passwordDiv").style.display = "block";
document.getElementById("loginbuttonDiv").style.display = "block";
document.getElementById("SeeSlide").style.display = "none";
} else {
console.log("this is not a mail")
}
}
<div id="QueryField">
<input type="text" id="IDQuery" placeholder="ID Kode">
<div style="display: none" id=passwordDiv><input type="password" id="passwordfield"><br></div>
<div style="display: none" id=loginbuttonDiv><button id="login" onclick="login()">log ind</button><br></div>
<button id="SeeSlide" onclick="imgMain()">Se Slide</button><br>
<br><br><br><br>
</div>

In your if statement you have if (iDCode = mail).
This re-assigns the value of mail to the variable iDCode. So the if effectively becomes if(mail) which is always true, because RegEx objects are truthy.
You should instead be checking if the input matches the regex, using either mail.test(iDCode) or iDCode.match(mail)

Few different ways. You can send an email to that address and check whether it bounces back or you can use PHP (I doubt you want to do this since your question is JavaScript) and send an email and then have them confirm it on the web address. Honestly, PHP is the best way to do this but since you're using JS you can try this from https://www.w3resource.com/javascript/form/email-validation.php:
function ValidateEmail(mail) {
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(myForm.emailAddr.value)) {
return (true)
}
alert("You have entered an invalid email address!")
return (false)
}
This works because we are checking all the invalid characters that are in an email address. If the input field contains any of those characters, its invalid.
Try Googling the answer. There are lots of information:
https://www.google.com/search?rlz=1C1GCEB_enUS865US865&ei=bn9dXuefDanJ0PEPofOHyAg&q=javacsript+check+email+address&oq=javacsript+check+email+address&gs_l=psy-ab.3..0i71l8.2549.3358..3533...0.2..0.0.0.......12....1..gws-wiz.........23%3A11-12j24%3A11-2.1hEMZpGGmWs&ved=0ahUKEwjnjr7N4vznAhWpJDQIHaH5AYkQ4dUDCAw&uact=5&safe=active&ssui=on

You can try using the .validate function. It works really great for checking login forms.
The function could look like the following:
$("#IDQuery").validate({
rules: {
email:
{required: true, email: true},
password:
{required: true}
},
messages: {
email:
{required: 'Please enter a E-mail',
email: 'Please enter a valid E-mail'},
password:{required: 'Please enter a password'}
},
errorPlacement: function (error, element) {
error.insertAfter(element.parent());
}
});

Related

How do I display an error message if the input is wrong on HTML

Im trying to display an error message in RED beside the input field to let the user know, however I dont know why my error message is not working. The requirement for the input is starting with a capital letter, followed by non special characters (any alphabets) please help me see what is wrong with my code
I am still new to HTML and I know many people said about regex but im not sure i have not learn that
<html>
<script>
function validateForm() {
var fname = document.getElementById("fname").value;
if (/^[A-Z]\D{2,30}$/.test(fname) == false)
{
document.getElementById("errorName").innerHTML = "Your email must be filled";
return false;
{
return name;
}
</script>
<style>
#errorName
{
color:red;
}
</style>
<form action="handleServer.php" method="get" onSubmit="return validateForm()">
<body>
<!-- starting with first name-->
First name: </br>
<input id="fname" type="text" name="fname" size="30">
<span id="errorName"></br>
<input type="submit" value="Submit">
</body>
</form>
</html>
I see your if statements are not closed properly and also the input box.
Please find codepan
function validateForm() {
console.log(1);
var fname = document.getElementById("fname").value;
if (/^[A-Z]\D{2,30}$/.test(fname) == false)
{
document.getElementById("errorName").innerHTML = "Your email must be filled";
return false;
{
return name;
}
}
}
When i tend to use regex i store it in its own value like this:
const patternName = /[0-9]|[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/|#]/;
let resultName = patternName.test(name.value);
The code above checks if the name contains anything from the regex above and if it does resultName will return true.
Next we can do the following:
If name is empty you get an error and it contains anything from the regex above we. In this case we show the error
If resultName is true we know that name contains something from the regex, so that it's not a valid name.
If not we show success message
if (name.value === "" || resultName) {
showErrorName();
} else {
showSuccessName();
}`

Email validation with jQuery, noobish problem [duplicate]

This question already has answers here:
How can I validate an email address in JavaScript?
(79 answers)
Closed 9 months ago.
Referring to this issue:
How can I set a minimum length for a field with jQuery?,
<form id="new_invitation" class="new_invitation" method="post" data-remote="true" action="/invitations" accept-charset="UTF-8">
<div id="invitation_form_recipients">
<input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_0"><br>
<input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_1"><br>
<input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_2"><br>
<input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_3"><br>
</div>
<input type="submit" value="Send invitation" name="commit">
</form>
What would the code be for settting a minimum length for a field with jQuery?
$('#new_invitation').submit(function(event) {
if ($('#invitation_form_recipients input').filter(function() {
return $(this).val();
}).length == 0) {
// All the fields are empty
// Show error message here
// This blocks the form from submitting
event.preventDefault();
}
});
How can I validate that every field input have a valid email address with jQuery? In the above code?
You probably want to use a regex like the one described here to check the format. When the form's submitted, run the following test on each field:
var userinput = $(this).val();
var pattern = /^\b[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i
if(!pattern.test(userinput))
{
alert('not a valid e-mail address');
}​
This regex can help you to check your email-address according to all the criteria which gmail.com used.
var re = /^\w+([-+.'][^\s]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
var emailFormat = re.test($("#email").val()); // This return result in Boolean type
if (emailFormat) {}
Email: {
group: '.col-sm-3',
enabled: false,
validators: {
//emailAddress: {
// message: 'Email not Valid'
//},
regexp: {
regexp: '^[^#\\s]+#([^#\\s]+\\.)+[^#\\s]+$',
message: 'Email not Valid'
},
}
},
This : /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i is not working for below Gmail case
gmail.#gmail.com
gmail#.gmail.com
Below Regex will cover all the E-mail Points: I have tried the all Possible Points and my Test case get also pass because of below regex
I found this Solution from this URL:
Regex Solution link
/(?:((?:[\w-]+(?:\.[\w-]+)*)#(?:(?:[\w-]+\.)*\w[\w-]{0,66})\.(?:[a-z]{2,6}(?:\.[a-z]{2})?));*)/g
This :
var email = /^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$/;
function mailValidation(val) {
var expr = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (!expr.test(val)) {
$('#errEmail').text('Please enter valid email.');
}
else {
$('#errEmail').hide();
}
}

Why HTML5 input type email doesn't allow empty space?

I use input type=email in my application. Prior to that in the old system developers user input type=text. Recently I was asked to fix the 'issue' in my code. The problem was reported by user when entering email address in the input field, accidentally empty space was entered on the end. Then user tried to Save the form, and error message was displayed under the email field This field is mistyped. I'm wondering if this is the way type=email should work and prevent empty space in the email address fields?
I tested this problem in Chrome and empty space will not be detected, but in Firefox will be and error message will show up.
$("#save").on("click", function() {
console.log(verifyFields('my-form'));
if (verifyFields('my-form')) {
alert('Saved!');
}
});
function verifyFields(containerID, includeInvisible) {
includeInvisible = includeInvisible || false;
let isValid = true;
const hdlMap = {
//'valueMissing': "This field is required",
//'patternMismatch': "This field is invalid",
'tooLong': "This field is too long",
'rangeOverflow': "This field is greater than allowed maximum",
'rangeUnderflow': "This field is less than allowed minimum",
'typeMismatch': "This field is mistyped"
};
const arrV = Object.keys(hdlMap);
const invalidInputs = [];
$("#" + containerID).find("input,textarea,select").each(function() {
var curItem$ = $(this);
var errMsg = [];
var dispfld = curItem$.data("dispfld");
var label = curItem$.data("label");
if (includeInvisible || curItem$.is(":visible")) {
if (curItem$[0].validity.valid) {
curItem$.removeClass("is-invalid");
return;
}
if (curItem$[0].validity['valueMissing']) {
var reqMsg = label ? label + " field is required" : "This field is required";
errMsg.push(reqMsg);
}
if (curItem$[0].validity['customError'] && dispfld) {
errMsg.push(dispfld);
}
if (curItem$[0].validity['patternMismatch'] && dispfld) {
errMsg.push(dispfld);
}
arrV.forEach(function(prop) {
if (curItem$[0].validity[prop]) {
errMsg.push(hdlMap[prop]);
}
});
if (errMsg.length) {
if (!curItem$.next().is(".invalid-feedback")) {
curItem$.after('<div class="invalid-feedback"></div>');
}
curItem$.addClass("is-invalid").next().text(errMsg.join(' and '));
invalidInputs.push(curItem$);
isValid = false;
} else {
curItem$.removeClass("is-invalid");
}
}
});
if (invalidInputs.length) {
invalidInputs[0].focus();
}
return isValid;
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="my-form" id="my-form">
<input type="email" name="user-email" id="user-email" required>
<button type="button" id="save">Save</button>
</form>
a space isn't a valid character for an input type="email" because we can't have email addresses with spaces in them (A).
So in this case you have an unfortunate scenario where the space isn't in the middle of the email address, but at the beginning or end. But if you look at the validation that the browser follows for this input type, it still won't be allowed.
You have two options:
Set it back to input type="text", but set the same validation pattern that applies for emails: <input type="text" pattern="/^[a-zA-Z0-9.!#$%&'*+\/=?^_{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$" /> and then modify that regex to allow for ending spaces (though you need to check on the back-end to make sure it will allow them, or otherwise you need to do a .trim() to remove those surrounding spaces.
Do a .trim() on your input after the user exits the input; removing whitespaces at the start or end.
(A) According to this answer:
space and "(),:;<>#[] characters are allowed with restrictions (they are only allowed inside a quoted string...

Regex for jquery password

I am busy using a jquery script that validates users password in real time. I would like to adjust it only accept a password if it has a letter, number and special character in it.
jQuery("#ValidEmail").validate({
expression: "if (VAL.match(/^[^\\W][a-zA-Z0-9\\_\\-\\.]+([a-zA-Z0-9\\_\\-\\.]+)*\\#[a-zA-Z0-9_]+(\\.[a-zA-Z0-9_]+)*\\.[a-zA-Z]{2,4}$/)) return true; else return false;",
message: "Please enter a valid Email ID"
});
jQuery("#ValidPassword").validate({
expression: "if (VAL.match(/^[^\\W][a-zA-Z0-9\\_\\-\\.]+([a-zA-Z0-9\\_\\-\\.]+)*\\#[a-zA-Z0-9_]+(\\.[a-zA-Z0-9_]+)*\\.[a-zA-Z]{2,4}$/)) return true; else return false;",
message: "Please enter a special character"
});
I am stumped on how to do this as it does not accept normaly regex experesions that I can find off the web eg
(/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8,})$/)
Any idea on how to solve this. Im bashing my head in here
As far as I can tell from the documentation, what you're using is not a supported syntax for adding validation methods to jQuery validate:
/* INCORRECT: */
jQuery("#element").validate({
expression: "if (/*...*/) return true; else return false;",
message: "Please enter a valid Email ID"
});
If you need custom validation rules, that is done with addMethod():
/* CORRECT: */
jQuery.validator.addMethod("methodname", function(value, element) {
// return true if value is valid
}, "message");
jQuery("#myform").validate({
rules: {
elementname: "methodname",
/* ... */
}
});
Your custom "email" validator is unnecessary; jQuery validate has its own. Here is an example of your password validator in action:
jQuery.validator.addMethod(
"myPasswordMethod",
function(value, element) {
// This is your regex, I have not looked closely at it to see if it is sensible
return value.match(/^[^\W][a-zA-Z0-9\_\-\.]+([a-zA-Z0-9\_\-\.]+)*\#[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/);
},
"Please enter a valid password"
);
$("#myForm").validate({
rules: {
pwd: "myPasswordMethod",
mail: "email" // don't reinvent the wheel; there is a built-in email validation method
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<form id="myForm">
<label for="mail">Email</label>
<input id="mail" name="mail"><br>
<label for="pwd">Password</label>
<input id="pwd" name="pwd"><br>
</form>
As discussed exhaustively in comments, clientside password validation (or any other clientside validation) is insufficient on its own. Validate on the client for the user's convenience; re-validate on the server to prevent user shenanigans or to handle disabled clientside scripting.

New reCaptcha with jQuery Validation Plugin

I searched and can't figure out how to validate the new reCaptcha, before form submit, along with the validate function of jQuery validation Plugin.
My intent:
$.validator.addMethod('reCaptchaMethod', function (value, element, param) {
if (grecaptcha.getResponse() == ''){
return false;
} else {
// I would like also to check server side if the recaptcha response is good
return true
}
}, 'You must complete the antispam verification');
$("#form").validate({
rules: {
name: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
reCaptcha: {
reCaptchaMethod: true
}
},
messages: {
name: "Please fill your name",
email: "Please use a valid email address"
},
submitHandler : function () {
$.ajax({
type : "POST",
url : "sendmail.php",
data : $('#form').serialize(),
success : function (data) {
$('#message').html(data);
}
});
}
});
In a few words: I would like to check server-side, with the remote method, if the user has passed the recaptcha validation BEFORE submitting the form, along with other rules of validation.
I'm able to check the recaptcha AFTER submission (on sendmail.php), but it would be nicer to have the recaptcha validation response along with other fields validation.
The main reason is for a better user experience, having all fields checked at once.
I've managed to achieve this, moving the check inside the submitHandler:
submitHandler : function () {
if (grecaptcha.getResponse() == ''){
// if error I post a message in a div
$( '#reCaptchaError' ).html( '<p>Please verify youare human</p>' );
} else {
$.ajax({
type : "POST",
url : "sendmail.php",
data : $('#form').serialize(),
success : function (data) {
$('#message').html(data);
}
});
}
}
But I don't like this approach, for 2 reasons:
It is just checking if the recaptcha has been filled, not if it's valid, and
User feels like it is a 2 step verification.
In this answer they say it can be done rendering the Recaptcha on a callback, to specify a function call on a successful CAPTCHA response.
I tried to implement that, but I've not been able to use this solution within a rule of the validate() function.
I know this question is a bit dated but I was having the same problem and just found the solution.
You can do this by adding a hidden field next to the reCaptcha div, like:
<div class="g-recaptcha" data-sitekey="{YOUR-SITE-KEY-HERE}"></div>
<input type="hidden" class="hiddenRecaptcha required" name="hiddenRecaptcha" id="hiddenRecaptcha">
then in your javascript:
$("#form").validate({
ignore: ".ignore",
rules: {
name: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
hiddenRecaptcha: {
required: function () {
if (grecaptcha.getResponse() == '') {
return true;
} else {
return false;
}
}
}
},(...rest of your code)
NOTICE THAT YOU MUST HAVE the ignore: ".ignore" in your code because jquery.validate ignores hidden fields by default, not validating them.
If you want to remove the error message on reCapcha validate add a data-callback to the reCapcha element
<div class="g-recaptcha" data-sitekey="{YOUR-SITE-KEY-HERE}" data-callback="recaptchaCallback"></div>
And then in your js file add
function recaptchaCallback() {
$('#hiddenRecaptcha').valid();
};
You can also prevent the form submit in the submitHandler
$("#loginForm").validate({
rules: {
username: {
required: true,
minlength: 6
},
password: {
required: true,
},
},
submitHandler: function(form) {
if (grecaptcha.getResponse()) {
form.submit();
} else {
alert('Please confirm captcha to proceed')
}
}
});
I've found your solution to be interesting (#FabioG).
But, I've modified it for use a bit by myself and I'm willing to share the code for others to use.
I was working on an interactive form, that validated as you completed steps.
It was used for ordering food. Ergo, the form required verification and activation of the register button and it is using the latest reCaptcha to date (5/12/2016).
Also, this code handles expired reCaptcha, server-side verification via ajax (though not included - if someone needs it to feel free to comment on my answer and I'll edit it accordingly).
Let's get started.
The HTML code:
<form id="registerForm" method="get" action="">
<fieldset class="step-1">
<h4>Step One:</h4>
<span class="clock">Register under one minute!</span>
<label for="email-register" class="label">E-mail*</label>
<input id="email-register" name="email-register" type="email" value="" autocomplete="off"/>
<label for="password-register" class="label">Password*</label>
<input id="password-register" name="password-register" type="password" value="" autocomplete="off"/>
<div class="g-recaptcha" data-sitekey="6LeS4O8SAAAAALWqAVWnlcB6TDeIjDDAqoWuoyo9" data-callback="recaptchaCallback" data-expired-callback="recaptchaExpired" style="margin-top: 3rem;"></div>
<input id="hidden-grecaptcha" name="hidden-grecaptcha" type="text" style="opacity: 0; position: absolute; top: 0; left: 0; height: 1px; width: 1px;"/>
</div>
</fieldset>
<fieldset class="step-2">
<h4>Step two:</h4>
<span class="notice">All fields with a sign are required!*</span>
<label for="first-name" class="label">First Name*</label>
<input name="first-name" id="first-name" type="text" value="" />
<label for="last-name" class="label">Last Name*</label>
<input name="last-name" id="last-name" type="text" value="" />
<label for="address" class="label">Address*</label>
<input name="address" id="address" type="text" value=""/>
<label for="entrance" class="label">Entrance</label>
<input name="entrance" id="entrance" type="text" value=""/>
<label for="apartment-number" class="label">Apartment #</label>
<input name="apartment-number" id="apartment-number" type="text" value="" />
<label for="inter-phone" class="label">Interphone</label>
<input name="inter-phone" id="inter-phone" type="text" value=""/>
<label for="telephone" class="label">Mobile Number*</label>
<input name="telephone" id="telephone" type="text" value="" />
<label for="special-instructions" class="label">Special Instructions</label>
<textarea name="special-instructions" id="special-instructions"></textarea>
<div>
</fieldset>
<button class="button-register" disabled>Register</button>
</form>
So as you can see, the button for submission (".button-register") is initially disabled.
You can only enable it by filling the mandatory (*) fields.
Please, keep in mind that I didn't include any CSS. The form is on a bare minimum and is just for educational purposes.
Few things that differ from #FabioG, the answer is:
There is no need to hide the element or use the ".ignore". I've hidden it with inline CSS.
There is a response callback for successful reCaptcha and expired reCaptcha.
So, if your reCaptcha expires while filling out the form it will make it invalid and the button will be disabled again.
As well, the form uses an input field (the hidden input field) to pass the information onto AJAX(PHP later on) and verify it server-side (It is a potential security risk, I covered it more at the end of the text).
Let's move on to JavaScript/jQuery.
JavaScript/jQuery:
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
function recaptchaCallback() {
var response = grecaptcha.getResponse(),
$button = jQuery(".button-register");
jQuery("#hidden-grecaptcha").val(response);
console.log(jQuery("#registerForm").valid());
if (jQuery("#registerForm").valid()) {
$button.attr("disabled", false);
}
else {
$button.attr("disabled", "disabled");
}
}
function recaptchaExpired() {
var $button = jQuery(".button-register");
jQuery("#hidden-grecaptcha").val("");
var $button = jQuery(".button-register");
if (jQuery("#registerForm").valid()) {
$button.attr("disabled", false);
}
else {
$button.attr("disabled", "disabled");
}
}
function submitRegister() {
//ajax stuff
}
(function ($, root, undefined) {
$(function () {
'use strict';
jQuery("#registerForm").find("input").on("keyup", debounce(function() {
var $button = jQuery(".button-register");
if (jQuery("#registerForm").valid()) {
$button.attr("disabled", false);
}
else {
$button.attr("disabled", "disabled");
}
}, 1000));
jQuery("#registerForm").validate({
rules: {
"email-register": {
required: true,
email: true
},
"password-register": {
required: true,
minlength: "6"
},
"first-name": "required",
"last-name": "required",
address: "required",
telephone: "required",
"hidden-grecaptcha": {
required: true,
minlength: "255"
}
},
messages: {
"email-register": "Enter valid e-mail address",
"password-register": {
required: "Enter valid password",
minlength: "Password must be bigger then 6 chars!"
},
"first-name": "Required!",
"last-name": "Required!",
address: "Required!",
telephone: "Required!"
},
submitHandler: submitRegister
});
});
})(jQuery, this);
As you can see here, there are a few functions: recaptchaCallback() and recaptchaExpired().
recaptchaCallback() that is embeded via the data attribute data-callback, uses the grecaptcha.getResponse() to see if the reCaptcha is validated, if so it enters the token to the hidden input field and asks for re-validation via the jQuery("#registerForm).validate();.
However, if the reCaptcha expires in the meanwhile it will use the assigned function in the "data-expired-callback", to remove the token from the input field and ask for re-validation again which will fail because the field is empty. This is achieved with the function recaptchaExpired().
Later in the code, you can see that we added a jQuery keyup function, to check for re-validation and see if the user has passed on the required information to the input fields. If the information and the field validate successfully the keyup function will enable the Register button.
Also, I've used a debounce script (tnx, David Walsh) on keyup. So it doesn't cause browser lag. Since, there would be a lot of typing.
But, keep in mind if a user decides to circumvent the reCaptcha he can always just enter the "255" character long string to the input field. But, I've gone a step further and made an AJAX verification server-side to confirm the reCaptcha. Though, I haven't included it in the answer.
I think this code is a marginal improvement on the previous answer. If you have any questions or need the AJAX/PHP code feel free to comment. I'll supply it when I can.
Heres the codepen as well: reCaptcha with jQuery.validation
You can find all the information regarding the reCatpcha data-attributes and functions in their API here: reCaptcha API
Hope it helped someone!
Regards,
I struggled with this one today and ended up going with:
<form onsubmit="return $(this).valid() && grecaptcha.getResponse() != ''">
Which just feels like the simplest way to do it. Someone is bound to complain about putting js inline like that but I'm ok with it.

Categories