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();
}
});
});
});
})();
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 have a login page and I have the API for matching the password. If the password doesn't match it will show an error message but my problem is if the password is matching also it showing an error message. because am looping the data so every time it is checking I need to break the loop if it matches how to do. Here is my
code
HTML
$(document).ready(function() {
localStorage.removeItem('role');
$(".login-error").hide();
$("#login").on("submit", function(e) {
e.preventDefault();
var form_data = $('#login').serialize();
var username = $("#name").val();
var pwd = $("#password").val();
$.ajax({
url: "https://api.myjson.com/bins/qt7fk",
type: "GET",
dataType: "json",
success: function(data) {
console.log(typeof(data));
// alert(JSON.stringify(data));
var arr = data;
arr.forEach(function(obj) {
console.log('name: ' + obj.name);
console.log('password: ' + obj.role);
var pass = obj.password;
// var decryptedBytes = CryptoJS.AES.decrypt(obj.password, "password");
var bytes = CryptoJS.AES.decrypt(pass.toString(), 'password');
var plaintext = bytes.toString(CryptoJS.enc.Utf8);
// alert(plaintext);
var role = obj.role;
if (role == "User") {
if (username == obj.name && pwd == plaintext) {
alert("New role");
document.getElementById('message').innerHTML = "Success"
/* window.location.href = "./job-insert.html?role=" + role; */
} else {
$("#login p").removeClass("d-none");
}
} else {
if (username == obj.name && pwd == plaintext) {
alert("Login succes");
document.getElementById('message').innerHTML = "Success"
/* window.location.href = "./dashboard.html?role=" + role; */
} else {
$("#login p").removeClass("d-none");
document.getElementById('message').innerHTML = "Please enter a correct login and password"
}
}
})
},
error: function(data) {
console.log(data);
}
});
});
});
I have forked and break your code when the password gets matched. You may test this from here: code
$(document).ready(function() {
localStorage.removeItem('role');
$(".login-error").hide();
$("#login").on("submit", function(e) {
e.preventDefault();
var form_data = $('#login').serialize();
var username = $("#name").val();
var pwd = $("#password").val();
$.ajax({
url: "https://api.myjson.com/bins/qt7fk",
type: "GET",
dataType: "json",
success: function(data) {
console.log(typeof(data));
// alert(JSON.stringify(data));
var arr = data;
var BreakException = {};
try {
arr.forEach(function(obj) {
console.log('name: ' + obj.name);
console.log('password: ' + obj.role);
var pass = obj.password;
// var decryptedBytes = CryptoJS.AES.decrypt(obj.password, "password");
var bytes = CryptoJS.AES.decrypt(pass.toString(), 'password');
var plaintext = bytes.toString(CryptoJS.enc.Utf8);
// alert(plaintext);
var role = obj.role;
if (role == "User") {
if (username == obj.name && pwd == plaintext) {
alert("New role");
document.getElementById('message').innerHTML = "Success"
/* window.location.href = "./job-insert.html?role=" + role; */
} else {
$("#login p").removeClass("d-none");
}
} else {
if (username == obj.name && pwd == plaintext) {
alert("Login succes");
document.getElementById('message').innerHTML = "Success"
throw BreakException;
/* window.location.href = "./dashboard.html?role=" + role; */
} else {
$("#login p").removeClass("d-none");
document.getElementById('message').innerHTML = "Please enter a correct login and password"
}
}
})
} catch (e) {
if (e !== BreakException) throw e;
}
},
error: function(data) {
console.log(data);
}
});
});
});
NOTE: You can break forEach like other loops. To make this thing done you need to add your code in try-catch and throw exception when the password gets matched. That is what I have done in your above code.
I have an html form that is validated by Javascript, but since connecting to an external API the form submits before the API queries have returned
All of the alerts are triggering correctly, however the last line of code - if (rtn) {
$('#saleForm')[0].submit();
} -
is resolving before the api call data returns and therefore once I accept the alerts the form always submits (as rtn is always true).
I am using setTimeout to wait for the return in the two if() blocks, and have tried a do/whilst loop around submit but that didn't work.
Is there a method I can use to force the submit to wait until all the previous conditions have been checked, before if(rtn)?
$('#saleForm').off('submit').on('submit', function(e) {
e.stopPropagation();
e.preventDefault();
var rtn = true;
if (window.hasIntegration == 'no' && $('#eventDate').val() == '') {
alert('Please choose the event date and time.');
$('#eventDate').focus();
return false;
}
$('.itemValue').each(function() {
if ($(this).val() == '') {
alert('Please ensure all values are entered.');
$('#ticket-rows').focus();
rtn = false;
}
});
if (!$('#terms').is(':checked')) {
alert('Please accept the terms and conditions.');
return false;
}
// now use integration to validate user supplied details
if (window.integrationId == 2) {
window.foundApiSellerDetails = [];
window.sellerEmailMatch = [];
var apiShowSelected = document.getElementById("showDateTime");
var apiShowId = apiShowSelected.value;
var orderRefField = document.getElementById('order_reference');
var orderRef = orderRefField.value;
$.get('/' + id + '/api-seller-details/' + apiShowId + '/' + orderRef, function(data) {
if (data.length > 0) {
window.foundApiSellerDetails = 'yes';
$.each( data.result, function( key, value ) {
var apiOrderId = value.order.id;
var apiBuyerEmail = value.buyer.email;
var apiOrderToken = value.token;
$.get('/get-seller-email', function(data) {
if (apiBuyerEmail === data) {
window.sellerEmailMatch = 'yes';
} else {
window.sellerEmailMatch = 'no';
}
});
});
} else {
window.foundApiSellerDetails = 'no';
}
});
setTimeout(function(){
if (window.foundApiSellerDetails == 'no') {
alert('Sorry, we can\'t find any details with Order Reference ' + orderRef + '. Please check your order number or contact);
$('#order_reference').focus();
return false;
}
if (window.foundApiSellerDetails == 'yes' && window.sellerEmailMatch == 'no') {
alert('Sorry, your email doesn\'t match the buyers email for this order');
return false;
}
}, 1000);
}
if (rtn) {
$('#saleForm')[0].submit();
}
});
Thanks everybody! I have brought the submit function inside the setTimeout function, and then brought that whole block inside the $.get api call as per #Gendarme. I've also added else after the if integration == 2, to make the submit work if no integration exists. New code below. Works a treat now.
// now use integration to validate user supplied details
if (window.integrationId == 2) {
window.foundApiSellerDetails = [];
window.sellerEmailMatch = [];
var apiShowSelected = document.getElementById("showDateTime");
var apiShowId = apiShowSelected.value;
var orderRefField = document.getElementById('order_reference');
var orderRef = orderRefField.value;
$.get('/' + id + '/api-seller-details/' + apiShowId + '/' + orderRef, function(data) {
if (data.length > 0) {
window.foundApiSellerDetails = 'yes';
$.each( data.result, function( key, value ) {
var apiOrderId = value.order.id;
var apiBuyerEmail = value.buyer.email;
var apiOrderToken = value.token;
$.get('/get-seller-email', function(data) {
if (apiBuyerEmail === data) {
window.sellerEmailMatch = 'yes';
} else {
window.sellerEmailMatch = 'no';
}
});
});
} else {
window.foundApiSellerDetails = 'no';
}
setTimeout(function(){
if (window.foundApiSellerDetails == 'no') {
alert('Sorry, we can\'t find any details with Order Reference ' + orderRef + '. Please check your order number or contact);
$('#order_reference').focus();
return false;
}
if (window.foundApiSellerDetails == 'yes' && window.sellerEmailMatch == 'no') {
alert('Sorry, your email doesn\'t match the buyers email for this order');
return false;
}
if (rtn) {
$('#saleForm')[0].submit();
}
}, 1000);
});
} else {
if (rtn) {
$('#saleForm')[0].submit();
}
}
});
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);
}