I have a registration page that requires the user to fill in a noCaptcha reCaptcha, but the widget is not filling in the g-recaptcha-response field. When I submit the form, my Node app is using a script I wrote to submit the response to Google and verify that the captcha is valid. That part is correct, but the recaptcha widget just won't fill out the response textarea it adds to the page. However, the jQuery I wrote that checks the value of the response field lets the page go through if the captcha is checked, but not if it is unchecked like it is supposed to, but the field is still not filled out.
What I need: To find out why reCaptcha isn't filling out the field when I POST the form to my backend.
Below is my register page's code and the jQuery running the page:
<div id="registerCard" class="login-card">
<p class="profile-name-card">Narrify Account Registration</p><br>
<form id="registerForm" action="/register" method="post" role="form" data-toggle="validator" class="form-signin has-validation-callback">
<input type="text" name="firstName" required="" placeholder="First name" autofocus="" class="form-control">
<input type="text" name="lastName" required="" placeholder="Last name" class="form-control">
<input id="inputRegistrationEmail" type="email" name="email" required="" data-validation="email" placeholder="Email address" class="form-control">
<input type="email" required="" data-validation="confirmation" data-validation-confirm="email" placeholder="Email repeat" class="form-control">
<input id="inputRegistrationPassword" type="password" name="password" required="" data-validation="strength" data-validation-strength="2" placeholder="Password" class="form-control">
<input type="password" required="" data-validation="confirmation" data-validation-confirm="password" placeholder="Password repeat" class="form-control">
<div data-sitekey="[MYSITEKEY]" class="g-recaptcha"></div><br>
<button type="submit" class="btn btn-primary btn-block btn-lg btn-signin">Register</button>
</form>
<a id="login-link" href="#" onclick="showLoginForm()" class="forgot-password">Login</a>
</div>
The jQuery:
$(function() {
// Switch to either load an avatar from autocomplete or remove the loading bar
if($("#inputEmail").val() != "") {
updateAvatar();
} else {
$("#image-progress").fadeOut();
}
// Event Handlers for links and inputs
$("#inputEmail").change(updateAvatar);
var url = window.location.pathname;
if(url.substring(url.lastIndexOf("#") + 1) == "register")
showRegisterForm();
$.validate({ modules: "security" });
$("#registerForm").submit(function(e) {
var recaptcha = $("#g-recaptcha-response").val();
if(recaptcha == "") {
e.preventDefault();
alert("Please complete the captcha");
}
});
});
function updateAvatar() {
// Show the loading bar until it is removed by a new image loading
$("#image-progress").fadeIn();
// Set the avatar image based on the input of the Email field
$("#profile-avatar").attr("src", "https://secure.gravatar.com/avatar/" + md5($("#inputEmail").val().toLowerCase()) + "?d=identicon&r=pg");
// Set event handler to hide loading bar once the image loads
$("#profile-avatar").on("load", function() {
$("#image-progress").fadeOut();
});
}
function showResetForm() {
alert("test");
}
function showRegisterForm() {
$("#loginCard").fadeOut();
$("#registerCard").fadeIn();
}
function showLoginForm() {
$("#registerCard").fadeOut();
$("#loginCard").fadeIn();
}
Related
I make my JSON script with a form and a button, but when I demo it on someone, they can press the submit button whenever they like. Here is my code:
<form action="action_page.php" method="GET">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"<br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"<br><br>
</form>
All I need now is validation and how to lock or hide the button. I tried using <script> with function and getElementById but I simply do not know how to lock it. Here is the message that will be inputted when it is locked and the form isn't completed:
You have not finished the information input for the survey. Please
input "Your First Name" and "Your Last Name" to enter the survey.
When they finish, I will input a loading icon until fully loaded.
Code Language(s)
I use fiddles to make my code, so I use:
HTML
JSON
Pinch of jQuery (loading icon)
Answer Expectations
In my answers, I need:
Recommended Code Language
Code for note purposes
Crossed out attributes
Attributes before coding explanations
EDIT: I just noticed that I can use the disabled boolean attribute here, so all I need is validation to disable the boolean attribute so they can press the button.
Hello I recommend JavaScript but it is not secure at all. However its the most effective in this case. Here is the code: (Note that i changed the html too)
<form action="action_page.php" method="get" >
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname" onkeyup="inputEntries()"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname" onkeyup="inputEntries()"><br><br>
<button type="submit" name="submit" id="submit_btn" disabled="true">submit</button>
</form>
<script>
var fname_var = document.getElementById("fname");
var lname_var = document.getElementById("lname");
var submit_btn_var = document.getElementById("submit_btn");
function inputEntries(){
if(lname_var.value != "" && fname_var.value != "")
submit_btn_var.disabled = false;
else
submit_btn_var.disabled = true;
}
</script>
What it does is that if both input fields are empty the button is not clickable but if both are it can be clicked. hope it helped!
You can use either pure javascript or jQuery to validate.
In the below code you would see we are first binding a change event to the input field and getting its values. If both values are present, the disabled attribute of the submit button is removed. Else the opposite.
<p id="msg">You have not finished the information input for the survey. Please input "*Your First Name*" and "*Your
Last Name*" to enter the survey.</p>
<form action="action_page.php" method="GET">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"<br><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"<br><br><br>
<button type="submit" id="btn-submit">Submit</button>
</form>
$(document).ready(function(){
('#btn-submit').prop('disabled', true);
$("input[type=text]").change(function(){
if ($('#fname').val() && $('#lname').val()) {
$('#btn-submit').prop('disabled', false);
$('#msg').hide();
} else {
$('#btn-submit').prop('disabled', true);
$('#msg').show();
}
});
});
Stackblitz - https://stackblitz.com/edit/jquery-kgzhuo?file=index.html
I have three email forms on one page, all using the same class. When someone enters an email address and submits one of those forms, I want to validate the email address entered into that specific form. The problem that I'm having if is someone enters an email address for one of the later forms, it validates against the data in the first form. How can I make it so my validation function validates for the field into which the email address was entered without having to give each form a unique ID and have the validation code multiple times?
The validation code is below and code for one of the forms. Thanks!
<script>
function validateMyForm() {
var sEmail = $('.one-field-pardot-form-handler').val();
if ($.trim(sEmail).length == 0) {
event.preventDefault();
alert('Please enter valid email address.');
return false;
}
if (validateEmail(sEmail)) {
}
else {
event.preventDefault();
alert('Invalid Email Address. Please try again.'); }
};
function validateEmail(sEmail) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(sEmail)) {
return true;
}
else {
return false;
}
}
</script>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n" method="post" onSubmit="return validateMyForm();" novalidate>
<input class="one-field-pardot-form-handler" maxlength="80" name="email" size="20" type="email" placeholder="Enter Email Address" required="required" />
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
Rather than calling the method from the html onsubmit attribute, wire the whole thing up in jquery.
$('form.myform').submit(function(e){
var $theForm = $(this);
var $theEmailInput = $theForm.find('.one-field-pardot-form-handler');
validateEmail($theEmailInput.val());
});
If you have 3 forms, just target the email field (via the class) within the context of the form.
And, don't use inline HTML event attributes (onsubmit, etc.), there are many reasons why and you can read about those here.
Instead, do all your event binding with JavaScript/JQuery and then you won't need to worry about return false to cancel the event if you are already using .preventDefault(). Additionally, it's best to capture the event reference as an argument to the event callback function, instead of the global event object.
There were other items that should be adjusted as well, so see additional comments inline:
// Get all the form elements and set up their event handlers in JavaScript, not HTML
$("form").on("submit", validateMyForm);
function validateMyForm(evt) {
// First, get the form that is being filled out
var frm = evt.target;
evt.preventDefault();
// Now, just supply the form reference as context for the email search
// Notice the extra argument after the selector "frm"? That tells JQuery
// where within the DOM tree to search for the element.
var sEmail = $('.one-field-pardot-form-handler', frm).val();
// Just to show that we've got the right field:
$('.one-field-pardot-form-handler', frm).css("background-color", "yellow");
// ***************************************************************************
// No need to convert a string to a JQuery object and call .trim() on it
// when native JavaScript has a .trim() string method:
if (sEmail.trim().length == 0) {
evt.preventDefault();
alert('Please enter valid email address.');
}
// Don't have empty branches, reverse the logic to avoid that
if (!validateEmail(sEmail)) {
evt.preventDefault();
alert('Invalid Email Address. Please try again.');
}
}
function validateEmail(sEmail) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return filter.test(sEmail);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n"
method="post"
novalidate>
<input class="one-field-pardot-form-handler"
maxlength="80"
name="email"
size="20"
type="email"
placeholder="Enter Email Address"
required>
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n"
method="post"
novalidate>
<input class="one-field-pardot-form-handler"
maxlength="80"
name="email"
size="20"
type="email"
placeholder="Enter Email Address"
required>
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n"
method="post"
novalidate>
<input class="one-field-pardot-form-handler"
maxlength="80"
name="email"
size="20"
type="email"
placeholder="Enter Email Address"
required>
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
So a combination of #paul and #ScottMarcus' answers above ultimately got me to where I needed to go. Below is what I ended up with and it works as intended. As others have pointed out, I'm definitely a n00b and just learning javascript so certainly may not be perfect:
<script>
$('form.pardot-email-form-handler').submit(function(event) {
var theForm = $(this);
var theEmailInput = theForm.find('.one-field-pardot-form-handler');
var theEmailValue = theEmailInput.val();
function validateEmail(theEmailValue) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(theEmailValue)) {
return true;
} else {
return false;
}
}
if (!validateEmail(theEmailValue)) {
event.preventDefault();
alert('Invalid Email Address. Please try again.');
} else {
return true;
}
});
</script>
<div class="nav-email-form">
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n" method="post" class="pardot-email-form-handler" novalidate>
<input class="one-field-pardot-form-handler" maxlength="80" name="email" size="20" type="email" placeholder="Enter Email Address" required="required" />
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
</div>
I'm loading a form into a modal dialog on button click and attaching .ajaxForm() to it on load. ajaxForm() has a beforeSubmit function in which I call two functions to validate username and password fields and setting .setCustomValidity() on them. I imagined it would go something like this; clicking Submit validation is done in beforeSubmit and setCustomValidity is set on invalid fields; then, a message appears on submit attempt.
However, messages appear only after I click Submit the second time. The first time it does nothing.
This is the form.
<form method="POST" action="/scripts/register.php" id="register-form">
<input minlength="6" maxlength="15" type="text" id="user" name="user" oninput="setCustomValidity('')" placeholder="Username" required>
<input minlength="6" maxlength="15" type="password" id="pass" name="pass" oninput="setCustomValidity('')" placeholder="Password" required>
<input minlength="6" maxlength="15" type="password" id="confirm_pass" name="confirm_pass" oninput="setCustomValidity('')" placeholder="Confirm Password" required>
<input type="email" id="email" name="email" placeholder="E-mail" required>
<input type="submit" name="login" class="button" value="Login">
</form>
Loading form into a dialog
$( "body" ).on("click","#register",function(){
$(".modal-dialog").load("register-form.php", function(){
$('#register-form').ajaxForm({
beforeSubmit : function(){
check_password_validity();
check_username_validity();
}
});
});
$( ".dialog-overlay" ).addClass( 'dialog-overlay-open' );
});
And the two functions where I setCustomValidity:
function check_password_validity(){
var pass = $("#pass").val();
var pass2 = $("#confirm_pass").val();
if(!is_alnum(pass)){
$("#pass")[0].setCustomValidity("Samo alfanumerički znakovi, bez razmaka i posebnih znakova.");
return;
}
if(pass!=pass2){
$("#confirm_pass")[0].setCustomValidity("Lozinke se ne podudaraju!");
return;
}
}
function check_username_validity(){
var user = $("#user").val();
if(!is_alnum(user)){
$("#user")[0].setCustomValidity("Samo alfanumerički znakovi, bez razmaka i posebnih znakova.");
return;
}
$.post( "/scripts/check_username_exists.php", {username: user}, function( data ) {
if(data=="true"){
$("#user")[0].setCustomValidity("Korisnik s tim imenom već postoji.");
return;
}
});
}
This works and all, but the messages appear on second submit attempt, after Submit buttons is clicked the second time. It seems like I'm missing something simple but can't figure out what it is.
I have this simple reg form on Page1, which redirect user for Page2 which have advanced reg form:
<form action="" method="post" class="signup-field" novalidate="novalidate">
<input type="text" name="first_name" value="" size="40" class="" id="first_name" placeholder="First Name">
<input type="text" name="last_name" value="" size="40" class="" id="last_name" placeholder="Last Name">
<input type="email" name="email" value="" size="40" class="" id="email" placeholder="E-Mail">
<input type="checkbox" name="acceptance" value="1" class="" >
<input class="sign-up-button" type="submit" onclick="parent.location='page2.html'" value="SIGN UP NOW!">
</form>
So I need to save these 4 inputs value when user click "SIGN UP NOW!" button and when it redirect user to Page 2 form, values 'first_name', 'last_name', 'email' and 'checkbox' must be already filled in Page2 form.
I've tried this code on page1 for save data in SessionStorage:
jQuery( document ).ready(function() {
jQuery('.signup-field .sign-up-button').click(function() {
sessionStorage.setItem("first_name", document.getElementById('first_name').val);
sessionStorage.setItem("last_name", document.getElementById('last_name').val);
sessionStorage.setItem("email", document.getElementById('email').val);
});
});
And this code on page2 to restore:
jQuery(document).ready(function($) {
if (sessionStorage.getItem('first_name') == "first_name") {
return;
}
var first_name = sessionStorage.getItem('first_name');
if (first_name !== null)
$('#ws-plugin--s2member-custom-reg-field-first-name').val(first_name);
var last_name = sessionStorage.getItem('last_name');
if (last_name !== null)
$('#ws-plugin--s2member-custom-reg-field-last-name').val(last_name);
var email = sessionStorage.getItem('email');
if (email !== null)
$('#user_email').val(email);
});
However it's not working for me. What is wrong with my code?
This doesn't exists:
document.getElementById('email').val
Vanilla JS syntax should be:
document.getElementById('email').value;
I'm currently creating a mobile website. I'm using jquery mobile.
I've already implemented the login and I'm now working on the registration.
On the login page i've got a simple . On the registration I am then logging the inputs, but it seems that the fields "username" and "password" are empty, even though i've entered some text. This problem doesn't occur after refreshing the page or if I load the page directly from the address bar.
Pageinit is being triggered.
I've deleted the cache but the problem is still there. Does anyone know why this is happening?
Here my code:
<!-- PAGE LOGIN -->
<div data-role="page" id="pageregistration">
<div data-role="content">
<input name="username" id="username" type="text" size="45" maxlength="45" placeholder="Username">
<input name="email" id="email" type="text" size="45" maxlength="45" placeholder="Email">
<input name="password" id="password" type="password" size="45" maxlength="45" placeholder="Password">
<input name="passwordConfirm" id="passwordConfirm" type="password" size="45" maxlength="45" placeholder="Confirm Password">
<button id="register">Create Account</button>
</div>
<script>
$('#pageregistration').on('pageinit', function()
{
$("#register").click(function(e)
{
e.preventDefault();
var username = document.getElementById('username').value;;
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
var passwordConfirm = document.getElementById('passwordConfirm').value;
console.log("Username: " + username + ", email: " + email + ", password: " + password + " - " + passwordConfirm);
});
});
</script>
</div>
Try with this because pageinit is triggered on the page being initialized, after initialization occurs.
Means you are getting to the registration page from somewhere (Other page)
$(document).on("pageinit", "#pageregistration", function(event) {
// rest of the code
});
The problem was found thanks to Omar. I changed the IDs and everything worked as desired.