After refreshing the page the label contenct vanishes.
What should i change so that this won't happen?
var versuche = 3; //login attempts
function validate(){
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if ( username == "DjolePhillip" && password == "passwort12345")
{
alert ("Login erfolgreich");
window.location = "loggedin.html";
document.getElementById("loginname").innerHTML = username; //label gets the username
return false;
}
else{
versuche --;
alert("Du hast "+versuche+" uebrig;");
if( versuche == 0)// if no attempts left
{
document.getElementById("username").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
}
<div id="anmeldung">
<center id="anmeldename"><label id="loginname"></label></center>
</div>
There above is the full Code.
You have to persist the data somewhere. Server side with an ajax request, client side with SessionStorage or LocalStorage.
Example with LocalStorage
var localStorage = window.localStorage
var storedUsername = getUsernameInMemory()
var domUsername = getUsernameDomValue()
var username = storedUsername || domUsername || 'unknown'
if ( !isUsernameDefinedInDOM() ) {
setLoginname(username)
}
if ( isUsernameKnown() && !isUsernameDefinedInLocalStorage() ) {
storeUsername(username)
}
function isUsernameKnown () {
return username !== 'unknown'
}
function setLoginname (_username) {
document.getElementById('loginname').innerHTML = username
}
function storeUsername (_username) {
localStorage['username'] = _username
}
function getUsernameDomValue () {
return document.getElementById('username').value
}
function getUsernameInMemory () {
return localStorage['username']
}
function isUsernameDefinedInDOM () {
return !!getUsernameDomValue() // returns a boolean
}
function isUsernameDefinedInLocalStorage () {
return getUsernameDomValue() !== 'unknown'
}
Related
I am creating a login form which is limited to only 3 attempts then redirects the user. However, it quickly iterates from 3 to 0 at only 1 failed try then redirects the user. I have been trying but have been stuck at this.
Javascript loginUser code which runs upon submit:
function loginUser() {
var form = document.getElementById("myForm");
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
google.script.run.withSuccessHandler(function(output) {
var atmp = 3;
while(atmp > 0) {
if(output == 'TRUE') {
console.log("Success");
form.reset();
break;
}
else if (output == 'FALSE') {
console.log("Denied");
atmp--;
form.reset();
Swal.fire({
icon: 'error',
title: 'Wrong Username/Password! Please, try again.',
showCancelButton: false,
});
}
} if (atmp == 0) {
console.log("3 Failed attempts!");
// Redirect code here...
}
}).checkLogin(username, password);
}
Code.gs checkLogin function:
function checkLogin(username, password) {
var url = 'sheetLinkHere';
var ss= SpreadsheetApp.openByUrl(url);
var webAppSheet = ss.getSheetByName("users");
var find = webAppSheet.getDataRange().getDisplayValues().find(([, , c, d]) => c == username && d == password);
return find ? 'TRUE' : 'FALSE';
}
I tried placing the while loop at different parts of the code but still wont work for me.
I was finally able to fix it. Credits to #Ruben in the comment section for giving me an idea. I just placed the variable outside the function and used an if-statement instead.
var atmp = 2;
function loginUser() {
var form = document.getElementById("myForm");
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
google.script.run.withSuccessHandler(function(output) {
if(atmp == 0) {
//redirect code here...
}else if(atmp > 0) {
if(output == 'TRUE') {
console.log("Success");
form.reset();
}
else if (output == 'FALSE') {
console.log("Denied");
atmp--;
}
}
}).checkLogin(username, password);
}
I think you're trying to do something like this:
const
realPassword = "Melon",
input = document.querySelector('input'),
feedback = document.querySelector('span');
input.addEventListener('change', handlePasswordAttempt);
input.focus();
let attempts = 3;
function handlePasswordAttempt(event){
--attempts;
const attemptedPassword = input.value;
input.value = "";
input.focus();
if(attempts == 0){
feedback.textContent = "No login for you!";
input.setAttribute("disabled", "");
}
else if(attemptedPassword == realPassword){
feedback.textContent = "Qapla'!";
input.setAttribute("disabled", "");
}
else{
feedback.textContent = `Incorrect password. ${attempts} tries left.`;
}
}
<div>Enter password:<input></div><br/>
<div><span></span></div>
We have a Shopify store and i have a script which validates the email adress and writes out if the email address is not good, another script is checking if the form is filled out and if it's not - it's not letting the customer to pass the next stage based on ID selector.
I only need this email validator to do the same thing as the other script, write out an alert when the email address is not correct and don't let them pass to the next step.
Can someone help with this? How to do that?
Script which validates the email address:
const validateEmail = (email) => {
return email.match(
/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
);
};
const validate = () => {
const $result = $('#result');
const email = $('#email').val();
$result.text('');
if (validateEmail(email)) {
$result.text(email + ' e-mail address is valid!');
$result.css('color', 'green');
} else {
$result.text(email + ' Lūdzu, ievadiet derīgu e-pastu lai pabeigt pirkumu');
$result.css('color', 'red');
}
return false;
}
$('#email').on('input', validate);
Script which checks wheter the form was filled out or not:
document.getElementById("cart__checkout").onclick = function() {
let allAreFilled = true;
document.getElementById("myForm").querySelectorAll("[required]").forEach(function(i) {
if (!allAreFilled) return;
if (i.type === "radio") {
let radioValueCheck = false;
document.getElementById("myForm").querySelectorAll(`[name=${i.name}]`).forEach(function(r) {
if (r.checked) radioValueCheck = true;
})
allAreFilled = radioValueCheck;
return;
}
if (!i.value) { allAreFilled = false; return; }
})
if (!allAreFilled) {
alert('Lūdzu, ievadiet Jūsu e-pastu lai pabeigt pirkumu!');
}
};
Appreciate the help, what i'm missing here?
Thank you!
Use the email validation inside on onClick event like this and set the var allAreFilled false is email validation failed
document.getElementById("cart__checkout").onclick = function() {
let allAreFilled = true;
document.getElementById("myForm").querySelectorAll("[required]").forEach(function(i) {
if (!allAreFilled) return;
if (i.type === "radio") {
let radioValueCheck = false;
document.getElementById("myForm").querySelectorAll(`[name=${i.name}]`).forEach(function(r) {
if (r.checked) radioValueCheck = true;
})
allAreFilled = radioValueCheck;
return;
}
if (!i.value) { allAreFilled = false; return; }
});
/* Here email valdation */
const email = $('#email').val();
if( !email.match(
/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
)){
allAreFilled = false;
}
/* terms and condtions check */
if( !$('#CartTermsDrawer').is(':checked') ){
allAreFilled = false;
}
if (!allAreFilled) {
alert('Lūdzu, ievadiet Jūsu e-pastu lai pabeigt pirkumu!');
return;
}
};
I am able to get the information from the object I am using to store the form information, when the one tries to fire the submit without filling in the fields successfully, but when I enter all the information correctly I can't seem to obtain the same upon success?
var theForm = document.getElementsByTagName('form')[0];
var firstNameInput = document.getElementById('firstNameInput');
var lastNameInput = document.getElementById('lastNameInput');
var emailInput = document.getElementById('emailInput');
var stateInput = document.getElementById('stateInput');
var theButton = document.querySelector('input[type=submit]');
// Wire the form's submit event to a callback
theForm.addEventListener('submit', validate);
function validate(e) {
// Error tracking variable
var error = false;
// Do validations
var emailPattern = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var formData = {
'firstName': null,
'lastName': null,
'email': null,
'stateInput': null
}
if ((firstNameInput.value == '') || (firstNameInput.value == null)) {
firstNameInput.classList.add('invalid-input');
firstNameInput.nextElementSibling.style.display = 'block';
firstNameInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
if ((lastNameInput.value == '') || (lastNameInput.value == null)) {
lastNameInput.classList.add('invalid-input');
lastNameInput.nextElementSibling.style.display = 'block';
lastNameInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
if (!emailPattern.test(emailInput.value)) {
emailInput.classList.add('invalid-input');
emailInput.nextElementSibling.style.display = 'block';
emailInput.nextElementSibling.innerHTML = 'Please enter valid email address!';
error = true;
}
if ((stateInput.value == 'selectstate')) {
stateInput.classList.add('invalid-input');
stateInput.nextElementSibling.style.display = 'block';
stateInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
// If error, stop the event
if (error) {
e.preventDefault();
e.stopPropagation();
console.log('There is no data from the form: ');
for (var prop in formData) {
console.log(prop + ' : ' + formData[prop]);
}
return false;
} else {
formData['firstName'] = firstNameInput.value;
formData['lastName'] = lastNameInput.value;
formData['email'] = emailInput.value;
formData['stateInput'] = stateInput.value;
console.log('There is now data from the form: :) ');
for (var prop in formData) {
console.log(prop + ' : ' + formData[prop]);
}
return true;
}
}
I tried this:
var result = theForm.addEventListener('submit', validate);
if (result) {
console.log(result);
}
Any help would be appreciated!
According to w3schools.com, this function, addEventListener() does not return anything.
https://www.w3schools.com/jsref/met_element_addeventlistener.asp
If you'd like to know if the event listener is installed properly, you need to check if the function exists:
if(theForm.addEventListener){
theForm.addEventListener('submit', validate);
}else{
theForm.attachEvent('onclick', validate);
}
As you can see from the attached segments below I am running in testing mode and when I try to use the testing stripe cards specifically 4242424242424242 nothing is working. How can I debug this?
Console log of the Stripe error:
Stripe interface:
The JavaScript code in progress:
function process_payment(cardNumber, cardExpiration, cardVerification, zipCode, price){
var vpf = validate_payment_fields();
if(vpf === true){
process_stripe_api(cardNumber, cardExpiration, cardVerification, zipCode, price);
// $contentLoader.show();
// clear_cc_fields($cardNumber, $cardExpiration, $cardVerification, $zipCode);
// $paymentProcessorForm.submit();
}
}
function process_stripe_api(cardNumber, cardExpiration, cardVerification, zipCode, price){
Stripe.createToken({
number: cardNumber,
cvc: cardVerification,
exp_month: cardExpiration.substring(0,2),
exp_year: cardExpiration.substring(3,5),
price: price
}, stripeResponseHandler);
}
function stripeResponseHandler(status, response) {
if (response.error) {
debugger;
}
else {
console.log('passed!');
debugger;
}
}
function validate_payment_fields(){
var $cardNumber = jQuery('#card_number');
var $cardVerification = jQuery('#card_verification');
var $cardExpiration = jQuery('#card_expiration');
var $zipCode = jQuery('#zip_code');
$cardNumber.next('.help-error').remove();
$cardVerification.next('.help-error').remove();
$cardExpiration.next('.help-error').remove();
$zipCode.next('.help-error').remove();
trim_field($cardNumber);
var cardNumber = validate_card_number($cardNumber);
trim_field($cardExpiration);
var cardExpiration = validate_card_expiration($cardExpiration);
trim_field($cardVerification);
var cardVerification = validate_card_verification($cardVerification);
trim_field($zipCode);
var zipCode = validate_zipcode($zipCode);
if(cardNumber && cardExpiration && cardVerification && zipCode){
return true;
}
else{
return false;
}
}
function clear_cc_fields(cardNumber, cardExpiration, cardVerification, zipCode){
cardNumber.val('');
cardVerification.val('');
cardExpiration.val('');
zipCode.val('');
}
function validate_card_number(field){
var regTester = new RegExp("\\d{16}");
if(regTester.test(field.val())){
return true;
}
else{
field.after("<p class='help-error'>Credit Card Number is Invalid!</p>");
return false;
}
}
function validate_card_expiration(field){
var regTester = new RegExp("^((0[1-9])|(1[0-2]))\/((2009)|(20[1-2][0-9]))$");
if(regTester.test(field.val())){
return true;
}
else{
field.after("<p class='help-error'>Credit Card Expiration is Invalid!</p>");
return false;
}
}
function validate_card_verification(field){
var regTester = new RegExp("\\d{3}");
if(regTester.test(field.val())){
return true;
}
else{
field.after("<p class='help-error'>CCV is Invalid!</p>");
return false;
}
}
function validate_zipcode(field){
var regTester = new RegExp("\\d{5}");
if(regTester.test(field.val())){
return true;
}
else{
field.after("<p class='help-error'>Zip Code is Invalid!</p>");
return false;
}
}
function trim_field(field){
var tmp = jQuery.trim(field.val());
field.val(tmp);
return tmp;
}
A snippet from the view:
= javascript_include_tag 'https://js.stripe.com/v2/'
javascript:
Stripe.setPublishableKey("#{ENV['MY_STRIPE_PUBLISHABLE_KEY']}");
The form:
Make sure the Stripe key you're using is the test key and not the production key:
Your key should start with pk_test or sk_test
JSHint Problems. console and FBT are also not defined.
As a result my button in page-signup does not work.
................................................................................................................................................................
(function () {
var emailAddressIsValid = function (email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
};
var passwordsMatch = function (password, passwordConfirm) {
return password === passwordConfirm;
};
var passwordIsComplex = function (password) {
// TODO: implement password complexity rules here. There should be similar rule on the server side.
return true;
};
$(document).delegate("#page-signup", "pagebeforecreate", function () {
var $signUpPage = $("#page-signup"),
$btnSubmit = $("#btn-submit", $signUpPage);
$btnSubmit.off("tap").on("tap", function () {
var $ctnErr = $("#ctn-err", $signUpPage),
$txtFirstName = $("#txt-first-name", $signUpPage),
$txtLastName = $("#txt-last-name", $signUpPage),
$txtEmailAddress = $("#txt-email-address", $signUpPage),
$txtPassword = $("#txt-password", $signUpPage),
$txtPasswordConfirm = $("#txt-password-confirm", $signUpPage);
var firstName = $txtFirstName.val().trim(),
lastName = $txtLastName.val().trim(),
emailAddress = $txtEmailAddress.val().trim(),
password = $txtPassword.val().trim(),
passwordConfirm = $txtPasswordConfirm.val().trim(),
invalidInput = false,
invisibleStyle = "bi-invisible",
invalidInputStyle = "bi-invalid-input";
// Reset styles.
$ctnErr.removeClass().addClass(invisibleStyle);
$txtFirstName.removeClass(invalidInputStyle);
$txtLastName.removeClass(invalidInputStyle);
$txtEmailAddress.removeClass(invalidInputStyle);
$txtPassword.removeClass(invalidInputStyle);
$txtPasswordConfirm.removeClass(invalidInputStyle);
// Flag each invalid field.
if (firstName.length === 0) {
$txtFirstName.addClass(invalidInputStyle);
invalidInput = true;
}
if (lastName.length === 0) {
$txtLastName.addClass(invalidInputStyle);
invalidInput = true;
}
if (emailAddress.length === 0) {
$txtEmailAddress.addClass(invalidInputStyle);
invalidInput = true;
}
if (password.length === 0) {
$txtPassword.addClass(invalidInputStyle);
invalidInput = true;
}
if (passwordConfirm.length === 0) {
$txtPasswordConfirm.addClass(invalidInputStyle);
invalidInput = true;
}
// Make sure that all the required fields have values.
if (invalidInput) {
$ctnErr.html("<p>Please enter all the required fields.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
return;
}
if (!emailAddressIsValid(emailAddress)) {
$ctnErr.html("<p>Please enter a valid email address.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
$txtEmailAddress.addClass(invalidInputStyle);
return;
}
if (!passwordsMatch(password, passwordConfirm)) {
$ctnErr.html("<p>Your passwords don't match.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
$txtPassword.addClass(invalidInputStyle);
$txtPasswordConfirm.addClass(invalidInputStyle);
return;
}
if (!passwordIsComplex(password)) {
// TODO: Use error message to explain password rules.
$ctnErr.html("<p>Your password is very easy to guess. Please try a more complex password.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
$txtPassword.addClass(invalidInputStyle);
$txtPasswordConfirm.addClass(invalidInputStyle);
return;
}
$.ajax({
type: 'POST',
url: FBT.Settings.signUpUrl,
data:"email=" + emailAddress + "&firstName=" + firstName + "&lastName=" + lastName + "&password=" + password + "&passwordConfirm=" + passwordConfirm,
success: function (resp) {
console.log("success");
if (resp.success === true) {
$.mobile.navigate("signup-succeeded.html");
return;
}
if (resp.extras.msg) {
switch (resp.extras.msg) {
case FBT.ApiMessages.DB_ERROR:
case FBT.ApiMessages.COULD_NOT_CREATE_USER:
// TODO: Use a friendlier error message below.
$ctnErr.html("<p>Oops! A problem occured while trying to register you. Please try again in a few minutes.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
break;
case FBT.ApiMessages.EMAIL_ALREADY_EXISTS:
$ctnErr.html("<p>The email address that you provided is already registered.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
$txtEmailAddress.addClass(invalidInputStyle);
break;
}
}
},
error: function (e) {
console.log(e.message);
// TODO: Use a friendlier error message below.
$ctnErr.html("<p>Oops! A problem occured while trying to register you. Please try again in a few minutes.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
}
});
});
});
})();