Javascript user input validation - javascript

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');
}

Related

Alert windows for second function not popping up

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.

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

Do while loop until user enters valid input

I need to create a do while loop that accepts any user input until a number is entered. my loop doesn't execute as expected. please help.
can i do without the maximum and the minimum values?
var number;
var minimum = 1;
var maximum = 20
window.prompt("Please enter a number between 1 and 20");
do {
if (number >= minimum && number <= maximum)
break;
else(window.prompt("Invalid input, please enter a number between
1 and 20 "));
}
while (number < minimum || number > maximum);
The code below works for you.
It's basically the same as yours, but I made it much more efficient and readable.
A few things I changed for you was:
window.prompt and prompt do the same thing. In other words, the window is unnecessary typing, so use just prompt.
prompt alone just asks for an input. It doesn't store it anywhere, or do anything with it. For you to be able to do anything with it, you need to set the value of a variable to equal it. I set number to equal the prompt
You can use isNan() to check if it is a string or a number.
var number = prompt("Please enter a number between 1 and 20");
var minimum = 1;
var maximum = 20
do {
if (isNaN(number)) {
break;
}
else {
number = prompt("Please enter a valid number between 1 and 20");
}
}
while (!isNaN(number));

I want to put validation for the prime Number Program

If the user enters nothing in the prompt box then also it is showing "The num is prime", I have put validation below. Also if I enter "1" in prompt box, it is still showing "The num is prime".
var Num = prompt("Enter the Number");
var flag = 0;
if (isNaN(Num)) {
alert("please enter valid number");
}
for (var i = 2; i < Num; i++) {
if (Num % 2 === 0) {
flag = 1;
break;
}
}
if (flag === 0) {
alert("The num is prime");
}
else if (flag === 1) {
alert("The num is not prime");
}
Annoyingly, isNaN("") returns false, as if "" were a number. To fix the problem with the empty prompt, you're gonna need to check that Num.length > 0
The isNaN function is not intended to be used to check whether or not something can be interpreted as a number. It's intended to check if the provided value is the specific NaN value. My suggestion would be to attempt to convert the prompted string into a number and see if that conversion was successful.
var Num = parseInt(prompt("Enter the Number"), 10);
if(Number.isNaN(Num)) {
alert("please enter valid number");
}
Please note: this will not ensure that all provided values will be valid. For example, parseInt("ABC123") will return NaN as expected, but parseInt("123ABC") will return 123 and ignore the subsequent "ABC".
Regarding the issue with 1s, the code you have provided appears to mark all odd numbers as prime. Assuming you have written the part that determines whether or not an odd number is prime, you could have a special case to say "if the number is 1, it's not prime." That's because for many purposes, 1 acts like a prime number. Obviously, it's not the most elegant solution, but... it works.

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.

Categories

Resources