Alert windows for second function not popping up - javascript

I'm working on an assignment where I have to write a basic program that generates a random password based on certain criteria. I have written the following snippet of code to receive input from the user regarding the minimum and maximum values of the desired password length.
`
function writePassword() {
var passwordText = document.querySelector("#password");
passwordText.value = password;
function exit(){
return;
}
function numbersOnly(num){
return /^[0-9]+$/.test(num); //checks if input only contains numbers
}
function getPassMin() {
let passMin = prompt("Input the minimum length of your password in characters (If blank, defaults to minimum length of 8):");
if (passMin < 8 && passMin !== "" && passMin !== null) { //checks if value is at least 8, reprompts if not
alert("Sorry, the password must be at least 8 characters.");
getPassMin();
} else if (passMin > 128) { //checks if value is not more than 128, reprompts if not
alert("Sorry, the password cannot exceed 128 characters.");
getPassMin();
} else if (passMin == "" || (numbersOnly(passMin) === false && passMin !== null)) {
alert("Please input a valid number in numeric format.");
getPassMin();
} else if (passMin === null){ //terminates program if cancel is pressed
writePassword.exit();
}
}
function getPassMax() {
let passMax = prompt("Input the minimum length of your password in characters (If blank, defaults to maximum length of 128):");
if (passMax > 128 && passMax!== "" && passMax !== null) { //checks if value is not more than 128, reprompts if not
alert("Sorry, the password cannot exceed 128 characters.");
getPassMax();
} else if (passMax < 8) { //checks if value is at least 8, reprompts if not
alert("Sorry, the password must be at least 8 characters.");
getPassMax();
} else if (passMax == "" || (numbersOnly(passMax) === false && passMax !== null)) { //checks if value is not blank and does not contain any non-numeric characters, reprompts if not
alert("Please input a valid number in numeric format.");
getPassMax();
} else if (passMax < passMin){ //checks if value of getPassMax is not less than getPassMin, reprompts if not
alert("Maximum value cannot be less than minimum length. You specified the minimum length as " + passMin + " characters.");
getPassMax();
} else if (passMax === null){ //terminates program if cancel is pressed
writePassword.exit();
}
}
getPassMin();
getPassMax();
}
`
The prompts in the getPassMin() method all work as expected, however the getPassMax() method only returns the proper prompt if the input value is either greater than 128 or less than 8, i.e the first 2 conditions. All the others simply result in closing the dialog window. I am not currently receiving any errors at any point during execution. Am I missing something?
I have tried copying and reusing the code from the getPassMin() method, and I have also tried re-writing the code from scratch. No success with either.

Your method getPassMax() cannot see the variable passMin which is causing an error. You could declare the variable passMin outside the scope of both methods, set the value inside getPassMin() and then it can be read inside getPassMax().
Also, be careful. When you've checked the value from the prompt is not null or empty (and against your number pattern or use if (!isNaN(value)) { ... }) then you should convert the value to a number. Currently you are comparing numbers inside strings which won't give you correct results.
You can simply use let value = Number(input); and input will be converted to a number. Now your number comparisons will be correct.

Related

Find the output using typeof function

I am writing a code. And here I have a problem how can I fix that. I have an input line, it takes a string or a number. So I need to check what is the output and get the answer. I need to give a simple solution. So I can't use functions or something like that.
let input = prompt('Enter your text.');
if (typeof input === "string") {
alert("You have string.");
} else if (typeof input === "number" && input > 30) {
alert("number more than 30");
} else if (typeof input === "number" && input < 30) {
alert("number less then 30");
}
prompt will always return a string.
If you want to check whether the string is composed purely of numerical values, you could use a regular expression:
if (/^[+-]?\d+(?:\.\d+)?$/.test(input)) {
// then it's purely numerical
const num = Number(input.trim());
// perform more operations on the number
} else {
// it's not composed of only numerical characters
}
If you don't want to use a regex, you can use Number alone, but then you'll also include values like Infinity which might not be desirable, and since Number('') gives 0, you'll have to check for that separately:
const num = Number(input);
if (input.trim().length && !Number.isNaN(num)) {
// then it's a number, use num
}
Another approach that I'd recommend is to avoid prompt entirely. Consider using a proper modal instead, such as a form with an input box and a submit button.
In such a case, if you want to require a numeric input, just do:
<input type="number">
I had a similar problem a few weeks ago and this is what I did:
function testNumber(test) {
if (isNaN(test) === false) {
console.log("this is a number");
} else {
console.log("this is not a number");
}
}
testNumber(4); // number
testNumber("4") // number
testNumber("string") // not a number
You can replace "test" for a variable if you don't want to use a function
if (isNaN(myVar) === false) {}
And you may want to add more checks if you want to differentiate between 4 and "4"
You can do
let input = prompt('Enter your text.');
if(isNaN(Number(input))){alert("You have string.")};
if (Number(input) > 30) {
alert("number more than 30");
} else if (Number(input) < 30) {
alert("number less then 30");
}
So it can change all Stringed-numbers to numbers and check if they are number with the isNaN function

Javascript Eval() thinks first value is a function

I am writing a function that will evaluate expressions in an input field and return the sum.
Currently is working but I am running into an error that I just cannot figure out. Here is my code in Plunker.
function linkFunction(scope) {
var PO = 10;
scope.value = PO;
scope.result = '';
scope.Evaluate = function (input) {
if (input.match(/[a-zA-Z]/g) != null) { //to check if user has inputted a letter between a-z, case sensitive.
return alert("You must only use numbers, not letters")
} else if (input.match(/[!"^£$&[{}\]?\\##~<>_'|`¬:;,=]/g) != null) { //to check if user has inputted a special symbol
return alert("You must only use the symbols specified")
} else if (input.match(/\.\d*\.+/g) != null) { //to check if user has inputted a doubled decimal eg 10.2.2
return alert("You can only use 1 decimal point")
} else if (input.match(/\.{2,}/g) != null) {//to check if user has inputted a two decimals eg 10..1
return alert("You cannot put two decimals one after another")
}
// if (input.match(/\d*\(\d\W\d\)/g) != null){
// }
var percentPattern = /[0-9]*\.?[0-9]+%/g;
var expressionResults = input.match(percentPattern);
if (scope.enablePercentage) { //if parameter = 1, then do this code.
if (expressionResults != null) { //if user has entered into the input field
if (expressionResults.length > 1) { //if you user has finished the RegEx (%, is the end of the RegEx, so code will think its the end of the array, therefore you cannot add another %)
return alert("Too many % values");
} else {// user has met all requirements
var percentageValue = parseFloat(expressionResults) * PO / 100;
input = input.replace(expressionResults, percentageValue);
}
}
} else if (expressionResults != null) { //if parameter = 0, then do this code. Parameter is off, but user has entered percentage
return alert("You cannot use %");
}
scope.result = eval(input);
}
}});
If you write 10(5+3) it gives you an error
TypeError: 10 is not a function
Obviously if a user ran this code they would expect to see the value 80.
Eval thinks that 10() is a function.
Does anyone know how to fix this problem. Thanks
eval expects you to pass it JavaScript, not algebra.
If you want to multiply two values together then you must use a Multiplicative Operator.
10 * (5+3)

Javascript user input validation

My exercise is to force a user to type a number and check that it is less than 100. I think I've done this well but there is another case I don't know how to do. If the user does not type any number in the space, the program should show something like "you must type a number". How should I write the code?
var number=prompt('enter a number');
if (number<100){
newnumber=100-number;
document.write(number+'is less than 100 by'+ newnumber);
}else if(number>100){
document.write('type again');
}
You can determine if the users input is a valid number by using the isNaN function. I have also validated the blank character for you, as shown below.
var isValid = !isNaN(number) && number !== "";
Full snippet:
var number = prompt('enter a number');
number = number.replace(/\s/g, "");
var isValid = !isNaN(number) && number !== "";
if (isValid) {
if (number<100) {
newnumber=100-number;
document.write(number+'is less than 100 by'+ newnumber);
} else if(number>100) {
document.write('type again');
}
} else {
document.write("Looks like you didn't enter a valid number");
}
https://jsfiddle.net/ezgn5cv5/
var number = null;
while (number !== 0 && !number || number >= 100) {
number = parseInt(prompt('Enter a number, less than 100'));
}
document.write(
number +
' is less than 100 by ' +
(100 - number)
);
This puts us in a loop for whether or not the number is a valid integer (I assumed that's what you wanted, but you could change this to float or something else), and under 100. Only when the user's input is valid will it go to the line to output.
The second condition for the while loop is !number. This basically tests for falsy conditions, such as NaN or null. If parseInt() can't figure out what the user typed in for a number, it will return NaN. And, of course, we initialized the number variable to null.
The first condition for while is number !== 0 is actually required because of the second condition which tests for falsy. 0 is falsy, but 0 is a valid number less than 100, so we need to make sure that we let 0 be valid. Conditionals like these short circuit. That means that they are processed from left to right, and any condition failing the test will immediately bypass the conditional block of code below. If number is 0, we know that the whole condition is false and we can move on.
The third condition simply ensures we're under 100 by re-prompting if we're not.
Also, I should note that document.write() has some issues. It's better to select an element on the page and set its text.
Remove all spaces .replace(/\s/g, "").
Detect if user input a number using parseFloat() if you want to allow
user to input decimal numbers like 5.254 or only integers using
parseInt() like 5.
Then detect if number > 100 or number < 100.
See this example:
var number = prompt('enter a number');
number = number.replace(/\s/g, ""); //remove all spaces
if (number != "") { // if not empty
if (parseFloat(number) == number) { // if decimal/integer number
if (number < 100) {
newnumber = 100 - number;
document.write(number + ' is less than 100 by ' + newnumber);
} else if (number > 100) {
//number = prompt('enter a number');
document.write('type again');
}
} else {
//number = prompt('enter a number');
document.write('you must type a number');
}
} else { // if empty input
//number = prompt('enter a number');
document.write('shouldn\'t be empty');
}

Why is my code not able to recognize that a password contains characters?

I am making a login form. Before it submits, I check if all the fields are filled in. I also check if the password is longer than 7 characters and contains at least one number, at least one character, and no spaces. My current code keeps on telling me that I am missing a character no matter what I enter. This is the code:
if($("#password").val()==""){
error += "The password is required.<br>";
}
else if($("#password").val().length<8){
error += "Your password needs at least 8 characters.<br>";
}
else if($("#password").val().length >= 8){
var pass = $("#password").val().split("");
var hasNum = false;
var hasChar = false;
var hasSpace = false;
for(var i = 0; i < pass.length; i++){
if(pass[i] == " "){
hasSpace = true;
}
else if(Number(pass[i]) == NaN){
hasChar = true;
}
else if(Number(pass[i]) != NaN){
hasNum = true;
}
}
if(!hasChar){
error += "Your password must contain at least one character.<br>";
}
if(!hasNum){
error += "Your password must contain at least one number.<br>";
}
if(hasSpace){
error += "Spaces are not allowed in a password.<br>";
}
}
I first check for a space. Then I check if a character can be converted to a number. If not, then it must be a string. If it can be converted, it must be a number. Whatever I type in, it always says "Your password must contain at least one character". How can I fix this? I will give you more code if it is necessary.
The problem is that NaN compares unequal (via ==, !=, ===, and !==) to any other value, including to another NaN value:
NaN === NaN;// false
Number('S') == NaN; //false
Number(10) == NaN; //false
try to use isNaN() instead.

Number Validation Not Working

I have an input field thats only supposed to take numbers inbetween 1 and 4. If the number is inbetween 1 and 4, it runs some code. If not, it shoots an alert that tells the user to try again with a number between 1 and 4. Here is my code
var number = document.getElementById("num").value;
if(Number(number) === 1 || Number(number) === 2 || Number(number) === 3 || Number(number) === 4 ){
//success code here///
}
else if(Number(number) !== 1 || Number(number) !== 2 || Number(number) !== 3 || Number(number) !== 4) {
} alert("Please type a whole number between(and including) 1 and 4 into the input field.");
I learned that the '.value;' function returns a string, even if the value is a number. So I put the var 'number' in the Number(); function that converts it to a number.
The problem is, when I type 1 into the input field. It shoots the alert even though it equals 1. None of the other numbers work either. I checked the console, and there are no syntax errors(also according to DreamWeaver). Help would be highly appreciated :)
I think you made a simple mistake of putting your alert outside the else if clause.
However there are a few other things you can do to make that a little more readable and efficient.
// Call Number() here so you only have to do it once
var number = Number(document.getElementById("num").value);
// You can also do something like parseInt(document.getElementById("num").value)
// Now check to see if Number() or parseInt() actually parsed an integer out of their input
// and then check that if it's outside your number range
if (isNaN(number) || number < 1 || number > 4) {
alert("Please type a whole number between(and including) 1 and 4 into the input field.");
} else {
// Do Successful code
}
we can write like this also
var patt1 = /[1-4]/g;
if(patt1.test(number)){
//success code here///
}
else{
alert("Please type a whole number between(and including) 1 and 4 into the input field.");
}

Categories

Resources