Undefined JS password generator - javascript

I'm making a simple password generator that prompts the user for conditions for a password such as case, symbols, and numbers then generates a password on click.
I have set up functions to handle these, however, cannot get the password to actually generate.
I'm getting an error where the password that's generated is undefined?
//Password option input
const resultEl = document.getElementById("result");
var characters = prompt("How many characters should the password containt (8-128)");
var upperCase = prompt("Should the password contain uppercase Letters?");
var lowerCase = prompt("Should the password contain lowercase Letters");
var numbers = prompt("Should the password contain numbers?");
var symbols = prompt("Should the password contain symbols?");
var generateEl = document.getElementById("generate");
function randomFunc(input) {
if (input === "hasUpper") {
console.log("upper");
return getRandomUpper();
}
if (input === "hasLower") {
getRandomLower();
console.log("lower")
}
if (input === "hasNumbers") {
getRandomNumber();
console.log("numbers")
}
if (input === "hasSymbols") {
getRandomSymbol();
console.log("symbols")
}
}
if (characters > 7 && characters < 129) {
var length = parseInt(characters, 10);
console.log("length: " + length);
} else {
var length = false;
alert("Invalid Password length");
}
// if input is "yes" return true
if (upperCase.toLowerCase() === 'yes') {
var hasUpper = true;
console.log("upper: " + hasUpper);
}
if (lowerCase.toLowerCase() === 'yes') {
var hasLower = true;
console.log("lower: " + hasLower);
}
if (numbers.toLowerCase() === 'yes') {
var hasNumbers = true;
console.log("number: " + hasNumbers);
}
if (symbols.toLowerCase() === 'yes') {
var hasSymbols = true;
console.log("symbol: " + hasSymbols);
}
generateEl.addEventListener('click', function() {
resultEl.innerText = generatePassword(hasUpper, hasLower, hasNumbers, hasSymbols, length);
console.log("generatebut");
});
//Generate password function
function generatePassword(hasUpper, hasLower, hasNumbers, hasSymbols, length) {
//1. initialise password variable
let generatedPassword = '';
const typesCount = hasUpper + hasLower + hasNumbers + hasSymbols;
//console.log('typesCount ', typesCount);
const typesArr = [{
hasUpper
}, {
hasLower
}, {
hasNumbers
}, {
hasSymbols
}]
//3. loop over length call generator function for each type
for (let i = 0; i < length; i += typesCount) {
typesArr.forEach(function(type) {
const funcName = Object.keys(type)[0];
console.log('funcNames ', funcName);
generatedPassword = randomFunc(funcName);
});
}
//4. Add final password to password variable and return
const finalPassword = generatedPassword;
console.log("password: " + generatedPassword);
return finalPassword;
}
// Password generator functions
function getRandomLower() {
return String.fromCharCode(Math.floor(Math.random() * 26) + 97);
}
function getRandomUpper() {
return String.fromCharCode(Math.floor(Math.random() * 26) + 65);
}
function getRandomNumber() {
return String.fromCharCode(Math.floor(Math.random() * 10) + 48);
}
function getRandomSymbol() {
const symbols = "!##$%^&*()<>?,."
return symbols[Math.floor(Math.random() * symbols.length)];
}
<main class="container">
<header>
<h1 class="title">Password Generator</h1>
</header>
<section class="generator-box">
<h2 class="sub-title">Generate a Password</h2>
<div class="pass-div pass-hold">
<h3>Your secure Password</h3>
<span id="result"></span>
</div>
<section class="button-div">
<button href="#" class="button" id="generate">Generate</button>
</section>
</section>
</main>

The randomFunc function is only returning a character for the "hasUpper" condition. You need to explicitly return a character regardless of case like so:
function randomFunc(input) {
let randomChar;
if (input === "hasUpper") {
randomChar = getRandomUpper();
}
if (input === "hasLower") {
randomChar = getRandomLower();
}
if (input === "hasNumbers") {
randomChar = getRandomNumber();
}
if (input === "hasSymbols") {
randomChar = getRandomSymbol();
}
return randomChar;
}
The generatePassword function is overwriting the generatedPassword variable on every loop. So even if you were returning characters from randomFunc your final password would only ever be 1 character. I modified that and removed the redundant finalPassword variable like so:
function generatePassword(hasUpper, hasLower, hasNumbers, hasSymbols, length) {
let generatedPassword = '';
const typesCount = hasUpper + hasLower + hasNumbers + hasSymbols;
const typesArr = [{ hasUpper }, { hasLower }, { hasNumbers }, { hasSymbols }]
for (let i = 0; i < length; i += typesCount) {
typesArr.forEach(function(type) {
const funcName = Object.keys(type)[0];
generatedPassword = generatedPassword + randomFunc(funcName);
});
}
return generatedPassword;
}

Related

Why does Javascript give me a uncaught type null error?

I'm having some trouble with my Javscript for a project (Its own document we're not allowed to use inline JS) my only that I can find while attempting to execute my program is this
"payment.js:182 Uncaught TypeError: Cannot set property 'onsubmit' of null
at init (payment.js:182)".
Now this error does not show up on JSHint when I verify my code so I don't understand how to fix it, it would be great if someone could give me some help. Heres the code:
"use strict";
//validate form inputs from payment.html
function validate() {
var errMsg = "";
var result = true; //assumes no errors
//assign elements to variables
var mastercard_check = document.getElementById("mastercard").checked;
var visa_check = document.getElementById("visa").checked;
var express_check = document.getElementById("express").checked;
var credit_name = document.getElementById("credit_name").value;
var credit_number = document.getElementById("credit_number").value;
var credit_expiry = document.getElementById("credit_expiry").value;
var credit_vv = document.getElementById("credit_vv").value;
//validations for form
if (!(mastercard_check || visa_check || express_check)) {
errMsg += "Please choose a card type\n";
result = false;
}
if (credit_name.length > 40) {
errMsg += "Please enter a name for your credit card between 1-40 characters\n";
result = false;
}
else if (!credit_name.match(/^[a-zA-Z ]+$/)) {
errMsg += "Credit card name can only contain alpha characters\n";
result = false;
}
if (isNaN(credit_number)) {
errMsg = errMsg + "Credit card number must contain digits only\n";
result = false;
}
else if (credit_number.length < 15 || credit_number.length > 16){
errMsg = errMsg + "Credit card number must contian either 15 or 16 digits\n";
result = false;
}
else {
var tempMsg = checkCardNumber(credit_number);
if (tempMsg != "") {
errMsg += tempMsg;
result = false;
}
}
if (!credit_expiry.match(/^\d{2}-\d{2}$/)) {
errMsg = errMsg + "Credit Card expiry must follow the format mm-yy\n";
result = false;
}
if (!credit_vv) {
errMsg = errMsg + "Please enter a Credit Card Verification Value\n";
result = false;
}
if (errMsg != "") {
alert(errMsg);
}
return result;
}
//obtain the credit card type
function getCardType() {
var cardType = "Unknown";
var cardArray = document.getElementById("credit_type").getElementsByTagName("input");
for(var i = 0; i < cardArray.length; i++) {
if (cardArray[i].checked) {
cardType = cardArray[i].value;
}
}
return cardType;
}
//check hte card number matches the chosen card type
function checkCardNumber(credit_number) {
var errMsg = "";
var card = getCardType();
switch(card) {
case "visa":
if (!(credit_number.length == 16)) {
errMsg = "Visa number must contian 16 digits\n";
}
else if (!credit_number.match(/^(4).*$/)) {
errMsg = "Visa number must start with a 4. \n";
}
break;
case "mastercard":
if (!(credit_number.length == 16)) {
errMsg = "Mastercard number must contian 16 digits\n";
}
else if (!credit_number.match(/^(51|52|53|54|55).*$/)) {
errMsg = "Mastercard number must start with digits 51 through 55. \n";
}
break;
case "express":
if (!(credit_number.length == 15)) {
errMsg = "American Express number must contian 15 digits\n";
}
else if (!credit_number.match(/^(34|37).*$/)) {
errMsg = "American Express number must start with 34 or 37. \n";
}
break;
}
return errMsg;
}
//calculate total cost using the meal size and quantity chosen
function calcCost(size, quantity){
var cost = 0;
if (size.search("three") != -1) cost = 100;
if (size.search("four")!= -1) cost += 150;
if (size.search("five")!= -1) cost += 200;
}
//get the stored values
function getInfo(){
var cost = 0;
if(sessionStorage.firstname != undefined){
document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;
document.getElementById("confirm_address").textContent = sessionStorage.address + " " + sessionStorage.suburb + " " + sessionStorage.state + " " + sessionStorage.postcode;
document.getElementById("confirm_details").textContent = sessionStorage.email + " " + sessionStorage.phone;
document.getElementById("confirm_preferred").textContent = sessionStorage.preferred;
document.getElementById("confirm_package").textContent = sessionStorage.package;
document.getElementById("confirm_size").textContent = sessionStorage.size;
document.getElementById("confirm_quantity").textContent = sessionStorage.quantity;
cost = calcCost(sessionStorage.size, sessionStorage.quantity);
document.getElementById("firstname").value = sessionStorage.firstname;
document.getElementById("lastname").value = sessionStorage.lastname;
document.getElementById("street").value = sessionStorage.street;
document.getElementById("suburb").value = sessionStorage.suburb;
document.getElementById("state").value = sessionStorage.state;
document.getElementById("postcode").value = sessionStorage.postcode;
document.getElementById("phone").value = sessionStorage.phone;
document.getElementById("email").value = sessionStorage.email;
document.getElementById("preferred").value = sessionStorage.preferred;
document.getElementById("deal").value = sessionStorage.deal;
document.getElementById("quality").value = sessionStorage.quality;
document.getElementById("quantity").value = sessionStorage.quantity;
document.getElementById("extrabags").value = sessionStorage.extrabags;
document.getElementById("accomodation").value = sessionStorage.accomodation;
document.getElementById("travel").value = sessionStorage.travel;
document.getElementById("prohibiteditems").value = sessionStorage.prohibiteditems;
document.getElementById("disabilityprecaution").value = sessionStorage.disabilityprecaution;
}
}
function cancelBooking() {
window.location = "index.html";
}
function init() {
getInfo();
var payment = document.getElementById("payment");
payment.onsubmit = validate;
var cancel = document.getElementById("cancel");
cancel.onclick = cancelBooking;
}
window.onload = init;
It might be that the ID at var payment = document.getElementById("payment"); is wrong and JS can't find it, also if you are calling some function you should do it like this payment.onsubmit = validate(); check that the ID is correct.
make sure your <script> tag is in the last before the </body> tag. like below
<html>
<head>
</head>
<body>
<form>
</form>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
but not like this
<html>
<head>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form>
</form>
</body>
</html>

Login Validation Javascript

require the user to enter a username that is 3 or more alphanumeric characters.
o require the user to enter a password that is 8 or more characters.
I am working on a login form, I have create html, css, and javascript files. I have created the validation functions but when I load my html I don't see the validation messages.
var subButton = document.getElementById('submit', validation);
function validation(e) {
let data = {};
e.preventDefault();
console.log(e);
errors.forEach(function (item) {
item.classList.add("hide");
})
let error = false;
inputs.forEach(function (el) {
let tempName = el.getAttribute("userName");
if (tempName != null) {
el.style.borderColor = "#ddd";
if (el.value.length == 0 && required.includes(tempName)) {
addError(el, "Required Field", tempName);
error = true;
}
if (tempName == "email") {
let exp = /([A-Za-z0-9._-]+#[A-Za-z0-9._-]+\.[A-Za-z0-9]+)\w+/;
let result = exp.test(el.value);
if (!result) {
addError(el, "Invalid Email", tempName);
error = true;
}
}
if (tempName == "password") {
let exp = /[A-Za-z0-9]+$/;
let result = exp.test(el.value);
if (!result) {
addError(el, "Only numbers and Letters", tempName);
error = true;
}
if (!(el.value.length > 8)) {
addError(el, "Needs to be greater than 8 characters", tempName);
error = true;
}
}
data[tempName] = el.value;
}
})
}
function addError(el, mes, fieldName) {
let temp = el.nextElementSibling;
temp.classList.remove("hide");
temp.textContent = fieldName.toUpperCase() + " " + mes;
el.login.borderColor = "red";
el.focus();
}
I don't see the validation alerts

Wrong output when using a function

I have a function that calculates the price something.
When the age < 5 then price = 0,
when the age < 15 the price = price/2
and when age > 15 the price = price + price*0.15. The first 2 are working fine but the last one has a problem. When for example a put 100 on the price input and 26 on the age input the answer that it gives me is 10015.
<script>
function add(x, y) {
return x+y;
}
function Subtract(x, y) {
return x-y;
}
function Divide(x, y) {
return x/y;
}
function Multiply(x, y) {
return x*y;
}
var plusPrice = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
var plusButton = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
function updateClickCount() {
document.getElementById("clicks").innerHTML = plusButton();
if (document.getElementById("price").value !== '') {
document.getElementById("input").innerHTML = plusPrice();
}
}
function checkInputs() {
var price = document.getElementById("price").value;
var age = document.getElementById("age").value;
if( parseInt(price) < 0 || isNaN(parseInt(price))) {
window.alert("Please insert a valid price");
price = '';
}
if(parseInt(age) > 100 || parseInt(age) < 0 || isNaN(parseInt(age))){
window.alert("Please insert a valid age");
age = '';
}
}
function Calculate() {
var price = document.getElementById("price").value;
var age = document.getElementById("age").value;
if (document.getElementById("price").value !== '' && document.getElementById("age").value !== '') {
if (age<5) {
document.getElementById("demo").innerHTML = Subtract(price,price);
} else if (age < 15 && age >= 5) {
document.getElementById("demo").innerHTML = Divide(price,2);
} else {
document.getElementById("demo").innerHTML = add(price,Multiply(price,0.15));
}
} else {
window.alert("Please fill both age and price to calculate the amount you have to pay");
}
}
</script>
<body>
Please enter the price: <br>
<input type="text" id="price"><button onclick="document.getElementById('price').value = ''">Clear input field</button><br><br>
Please enter your age: <br>
<input type="text" id="age"><button onclick="document.getElementById('age').value = ''">Clear input field</button><br><br>
<button onclick="checkInputs(); updateClickCount(); Calculate();">Calculate price</button>
<p id="totalPrice">The total amount you have to pay is: </p><br>
<p id="demo"></p>
<p>Button Clicks: <a id="clicks">0</a></p>
<p>Correct Price Fill Count: <span id="input">0</span></p>
</body>
Apparently, price is a string. Replace
var price = document.getElementById("price").value;
with
var price = parseFloat(document.getElementById("price").value);
The function has already worked for subtraction and division, because operators - and / can't be applied to strings, so JS coerces them to numbers. The +, however, has a string-compatible interpretation (string concatenation), so type coercion doesn't happen.
or do this
var price = Number(document.getElementById("price").value);
In JavaScript the + symbol can be used both for numeric addition and string concatenation, depending on the variables either side. For example,
console.log('value:' + 4); // 'value:4'
console.log(3 + 1); // 4
console.log('value:' + 4 + '+' + 1); // 'value:4+1'
console.log('value:' + 4 + 1); // 'value:41'
console.log('value:' + (3 + 1)); // 'value:4'
console.log(4 + ' is the value'); // '4 is the value
Hence convert your operands to numeric type before proceeding with addition so that they are not concatenated.
Hope this clarifies.

Javascript code broken

This is my first attempt at a little more complex code structure. The thing is my IDE says it technically works , jsfiddle says it doesn't, it actually initializes only the two confirm functions that I declared "confirmUserName();" and "confirmFullName();"
Can someone explain why i did such a horrible job.
var userList = [];
var username = "";
var fullname = "";
var addUserName = addUser(username, userList); v
var addFullName = addUser(fullname, userList);
function addUser(usrName, list) {
if(list.length == 0) {
list.push(usrName); // userlist empty add the new user
} else {
for (var i = 0; i < list.length; i++) {
if(list[i] == undefined) {
list[i] = usrName;
return list;
} else if(i == list.length - 1) {
list.push(usrName);
return list;
}
}
}
} // Function that adds user and name to list
var usernameQuery;
function confirmUserName() {
confirm("Is " + username + " your first choice?");
if (confirmUserName == true) {
return fullnameQuery;
} else {
return usernameQuery;
}
}
var fullnameQuery; /
function fullnameConfirm() {
confirm("Is " + fullname + " your first choice ");
if (fullnameConfirm == true) {
return startRide;
} else {
return fullnameQuery;
}
}
if(username == undefined) {
usernameQuery = function() {
username = prompt("You are the first user to play, \n" +
" Chose and let the game begin !");
return addUserName;
};
} else {
usernameQuery = function() {
username = prompt("What username whould you like to have ? \n" +
" Chose and let the game begin !");
return addUserName;
};
}
confirmUserName();
if(fullname == undefined) {
fullnameQuery = function() {
fullname = prompt("Enter your real name !");
return addFullName;
};
} else {
fullnameQuery = function() {
fullname = prompt("Enter your real name!");
return addFullName;
};
}
fullnameConfirm();
There is a lot wrong with the code you posted -- I'll just take one chunk:
function confirmUserName() {
// The return value of `confirm` is ignored.
confirm("Is " + username + " your first choice?");
// confirmUserName is the name of your function.
// You sould be using `===` instead of `==`
// Or, not comparing against true at all.
if (confirmUserName == true) {
return fullnameQuery;
} else {
return usernameQuery;
}
}
Fixed function:
function confirmUserName() {
var res = confirm("Is " + username + " your first choice?");
if (res) {
return fullnameQuery;
} else {
return usernameQuery;
}
}
It does not throw Errors with this, but I dont know in which situation you want your code to be implemented and what it should do, I hope this is what you need:
var userList = [];
var username = "";
var fullname = "";
var addUserName = addUser(username, userList);
var addFullName = addUser(fullname, userList);
function addUser(usrName, list) {
if (list.length === 0) {
list.push(usrName); // userlist empty add the new user
} else {
for (var i = 0; i < list.length; i++) {
if (list[i] === undefined) {
list[i] = usrName;
return list;
} else if (i == list.length - 1) {
list.push(usrName);
return list;
}
}
}
} // Function that adds user and name to list
var usernameQuery;
function confirmUserName() {
confirm("Is " + username + " your first choice?");
if (confirmUserName === true) {
return fullnameQuery;
} else {
return usernameQuery;
}
}
var fullnameQuery;
function fullnameConfirm() {
confirm("Is " + fullname + " your first choice ");
if (fullnameConfirm === true) {
return startRide;
} else {
return fullnameQuery;
}
}
if (username === undefined) {
usernameQuery = function () {
username = prompt("You are the first user to play, \n" +
" Chose and let the game begin !");
return addUserName;
};
} else {
usernameQuery = function () {
username = prompt("What username whould you like to have ? \n" +
" Chose and let the game begin !");
return addUserName;
};
}
confirmUserName();
if (fullname === undefined) {
fullnameQuery = function () {
fullname = prompt("Enter your real name !");
return addFullName;
};
} else {
fullnameQuery = function () {
fullname = prompt("Enter your real name!");
return addFullName;
};
}
fullnameConfirm();

more than currency input field

I have this input tag where you put the total of your receipt :
<input type="text" name="currency" id="currency" class="text-input" onBlur="this.value=formatCurrency(this.value);" />
The Javascript is as follows:
<script type="text/javascript">
function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num)) {
num = "0";
}
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num % 100;
num = Math.floor(num/100).toString();
if(cents < 10) {
cents = "0" + cents;
}
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) {
num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
}
return (((sign)?'':'-') + '$' + num + '.' + cents);
}
</script>
Users can only enter receipts more than $10.00 bucks, how can I set that on my script? Also they need to know they can not enter currency less than $10.
From what I can gather from your question I think you are looking for something like this. Basically if we have a valid entry such as $100.00 we continue, return true etc, else if we have something that looks like an int or float we can reformat this and recurse the function, else hint user for of vaild entry
var foo = document.getElementById('foo');
foo.addEventListener('blur', function(e) {
var val = e.target.value;
var err = document.getElementById('err');
var errMsg = 'please enter a value $10.00 or greater';
var patt = /^\$\d+\.\d{2}$/;
var amount = parseInt(val.replace(/\$|\./g, ''));
if (val !== '') {
if (patt.test(val)) {
if (amount < 1000) {
err.textContent = errMsg;
} else {
document.getElementById('suc')
.textContent = 'processing request';
}
} else if (typeof amount == 'number' && !/[a-z]/g.test(val)) {
if (/\.\d{2}/.test(val)) {
e.target.value = '$' + (amount / 100);
} else {
e.target.value = '$' + amount + '.00';
}
arguments.callee(e);
} else {
err.textContent = errMsg;
}
}
});
here is a demo
You can apply a validation function when submitting the form to test if the value is below a threshold, such as:
function validate()
{
value = document.getElementById('currency');
if (value <= 10.00)
{
return false
} else
{
return true;
}
}
You could also apply this to the onblur event, but my preference is to present validation errors when the form is submitted.
It looks like you're trying to parse a string, convert it nicely into dollars and cents, and reject it if it's less than 10. There's a much nicer way to do that:
function formatCurrency(num) {
// Remove the dollar sign
num = num.replace("$", "");
// Change the string to a float, and limit to 2 decimal places
num = parseFloat(num);
Math.round(num * 100) / 100;
// If its less than 10, reject it
if(num < 10) {
alert("Too small!");
return false;
}
// Return a nice string
return "$" + num;
}
At the end, are you trying to return -$99.94 if the number is negative?

Categories

Resources