Can I use a while loop to validate a prompt input? - javascript

I am doing a project in a Javascript course and I need to check the conditions to make sure that the correct information is being passed in.
I am trying to learn to think like a programmer so my first solution only checked the conditions once. Seeing that as a problem I tried to think of a way to keep checking the conditions until all the information was correct. I am trying to use a while loop but I am not able to get it working.
My logic is as long as lastname is not equal to NaN OR lastname.value is less the 4 char long OR lastname is equal to null. Keep asking for there last name. If any of those conditions are true keep asking for there last name until they are all false.
I want to use a while loop for the gender prompt to but I am not sure what I am doing.
I am new and not really sure where I went wrong in this?
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Conditionals</title>
<script>
/*
Write the greetUser() function that prompts the user
for his/her gender and last name and stores the results
in variables.
For gender:
If the user enters a gender other than "Male" or "Female",
prompt him/her to try again.
For last name:
If the user leaves the last name blank, prompt him/her to
try again.
If the user enters a number for the last name, tell the user
that a last name can't be a number and prompt him/her to try again.
After collecting the gender and last name...
If the gender is valid, pop up an alert that
greets the user appropriately (e.g, "Hello Ms. Smith!")
If the gender is not valid, pop up an alert
that reads something like "XYZ is not a gender!"
*/
function greetUser() {
var gender, lastname;
gender = prompt("are you a Male or Female? ");
if (gender != "Male" && gender != "Female") {
gender = prompt("Try again: Male or Female?");
}
lastname = prompt("And what is your last name?")
while (lastname != NaN || lastname.value < 4 lastname == null); {
lastname = prompt("Please try again. What is your last name?");
}
}
</script>
</head>
<body onload="greetUser();">
<p>Nothing to show here.</p>
</body>
</html>

function greetUser() {
var gender, lastname;
gender = prompt("are you a Male or Female? ");
while (gender !== "Male" && gender !== "Female") {
gender = prompt("Try again: Male or Female?");
}
lastname = prompt("And what is your last name?")
while (lastname === '' || lastname.length < 4 || lastname === null) {
lastname = prompt("Please try again. What is your last name?");
}
}
greetUser();
I made little fixes to your code.
Your while loop has incorrect logical operators, this the correct version: while (lastname === '' || lastname.length < 4 || lastname === null) Further, you were comparing lastname !== ''.
For the gender prompt you need to execute a while loop while (gender !== "Male" && gender !== "Female").
Hope it helps!

Related

Javascript:How to break a while loop when a condition is met to make it so that the loop is terminated when a Var is not null (Break Not Working

var Age;
Age = prompt("How old are you");
while (Age === null){
prompt("Please Cofirm You Name");
if (Age > 0 ){
break;
}
}
I am trying to make it so that the user is in a loop until var Age is not null... My goal is to make it so that you cant cancel the prompt and have to type in it. I have tried using the break; in an if statement but its not working.
When I use the break; in an if statement it continues to send the prompt
Is there another way to do this
Or is the value of var Age equal to null(even if you add an integer greater then 0) for some reason and if it is anyone know how to fix it
is there are better way to make to user type in the prompt
Thank You in advanced
var Age = prompt("How old are you?");
Age = Number(Age);
while (isNaN(Age) || Age < 1) {
Age = prompt("Please confirm your age.");
Age = Number(Age);
}
In the prompt dialog box, the user can enter anything. So we are trying to see if the user has entered a number by using Number(Age) which tries to parse the user entered value as a number, and returns a number if it is a number.
That means if the user entered value is number, then Age will have a valid number (but it might be negative, which is invalid for our use case). Anything other than a number will give either NaN or 0.
So, when you write Age = Number(Age),
Age might be assigned with a proper number (positive or negative), or
NaN (NaN stands for not a number and it is considered a type of
data in JS), or
0 when user enters space(s).
In the while loop condition, we are checking whether the user entered value is invalid. That is, is Age not a number? or is Age less than 1?.
The || operator used between these two conditions will return true if any one of these two conditions is true (in fact, if the first condition is true, it doesn't even bother to check the second condition, and simply returns true). It returns false if both of the conditions are false.
So, if the user has entered invalid input (negative number or space or string), we prompt the user till he enters a proper value.
A while-loop has a break, look at this simple example.
let a = 2;
while (a <100) {
console.log(a);
a *= 2;
if (a===16)
break;
}
Try with do-while:
let age, age2;
do {
age = prompt("How old are you?");
} while (age === "");
do {
age2 = prompt("Please Cofirm Your age");
} while (age2 === "" || age2 !== age);

Confusion with prompts and alerts

<!DOCTYPE html>
<html lang="en">
<script type="text/javascript">
<!--
var Name = prompt("Enter Your Name");
var Age = prompt("Enter Your Age. This should be an integer.");
if (Age < 12) {
alert("Sorry, You must be at least 12 to enter this site!");
exit }
var Sex = prompt("Enter Your Sex. This should be a single letter input F or M");
if (Sex != "M", "F") {
alert("Sex must be a single letter F or M");
}
// -->
</script>
Im trying to get only an "M" of "F" from the Sex prompt, but I'm really not sure how to do that. Right now it gets to the end of the code and no matter what I type into the Sex prompt the alert "Sex must be a single letter F or M" pops up. Any help would be greatly appreciated, I've been stumped for a couple days now.
In JavaScript and most other similar-looking languages, you have to be fairly verbose when checking against two values:
if (Sex != "M" && Sex != "F") {
Each part (Sex != "M" and Sex != "F") is a complete != expression, and then the overall thing is an && ("and") expression.
There are other ways to do it (a switch, or a fairly obscure thing like if (!["M", "F"].includes(Sex))), but the above is the standard way to do a simple check against two values.

Validate that multiple Prompts have a value

I´m trying to write a simple test where I ask for name and age in separate Prompts. I´d like to validate user really adds a value in both prompts.
What´s the best way to do this validation without duplicating code?
When I click "OK" with no value, it does not ask me to add a value
function showInfo() {
//Asking for name in a prompt
var name = prompt("Name: ","");
//Checking if it is null or empty
if (name == null || ""){alert("Please enter your name");}
//Same for age
var age = prompt("Age: ","");
if (age == null || ""){alert("Please enter your age.");}
}
Also, noticed that "null" is to check the "Cancel" button, but I was able to test that if you click "Cancel", and click "Cancel" again, it does not ask for a value. How can I solve this issue?
You if condition is wrong. You should use
if (name === null || name === "") {
//you code here
}
And If you like to show prompt continusly unless user enters input below code will work:
function showInfo() {
while(1) {
//Asking for name in a prompt
var name = prompt("Name: ","");
if (name === null || name === ""){alert("Please enter your name");}
else break;
}
console.log("Name= "+name);
while(1) {
//Same for age
var age = prompt("Age: ","");
//Checking if it is null or empty
if (age === null || age === ""){alert("Please enter your age.");}
else break;
}
console.log("Age ="+age);
}
showInfo();
You could put it in a loop to ask again. Here I'm using !name to check for the
"truthyness" of name. null and an empty string are both "falsy" so, !name
will return true for them, a non-empty string is truthy, so !name will
return false for them.
function ask (msg, errMsg) {
var name;
do {
name = prompt(msg);
//Checking if it is null or empty
if (!name) {
alert(errMsg);
}
} while (!name);
return name;
}
function showInfo() {
var name,
age;
name = ask("Name:", "Please enter your name");
age = ask("Age:", "Please enter your age.");
}
showInfo();
That said, unless this is just a prototype or a small personal project only you
will use, don't do it this way! Sticking the user in a loop prompt will
frustrate most people. Most modern browsers include a "Don't show me this again"
check box. I'm not sure what would happen if the user checks it, the browser
might continue in an infinite loop and lock up or crash.
Instead it would be better to do it with a form on the page:
var elShowInfo = document.getElementById('show-info'),
elName = document.getElementById('name'),
elAge = document.getElementById('age'),
elOut = document.getElementById('output');
function showInfo (ev) {
// stop the form from submitting
ev.preventDefault();
var name = elName.value,
age = elAge.value;
if (name && age) {
// do something with name/age
elOut.textContent = name + ' is ' + age + ' years old.';
}
}
elShowInfo.addEventListener('click', showInfo, false);
<form>
<label for="name">Name:</label> <input id="name" placeholder="Please enter your name">
<label for="age">Age:</label> <input id="age" placeholder="Please enter your age">
<button id="show-info">Show info</button>
</form>
<div id="output"></div>
Every time the Show Info button is pressed it checks for the data once and then does something with it if it is there; otherwise it does nothing.
One thing to note, both prompt and the .value property of an element return strings so if you are going to use age to do some sort of calculation you will need to convert it to a number either using parseInt, age = parseInt(age, 10) or an unary +, age = +age;.
Further reading:
Truthy and Falsy: When All is Not Equal in JavaScript
Introduction to the DOM
#Arshad answer adds more clarity.
on a side note, the reason why the || didn't work is the order of evaluation.
if (age == null || "") --> evaluated as
if ((age == null) || "") --> true on Cancel, false on Ok
Hope this helps !

Require user to choose 'boy' or 'girl'

I am trying to get my user to respond to the question "are you a boy or a girl?" with one of those two choices and force them to choose one or the other.
I think I am heading in the right direction but whenever i run my code, it hiccups if choosing the second option.
What am i doing wrong?
var gender = prompt("Are you a boy or a girl?").toLowerCase();
while (gender !== ("boy" || "girl")) {
gender = prompt("Please only respond with boy or girl. Now, are you a boy or a girl?");
}
Personally I like
var gender = prompt("Are you a boy or a girl?").toLowerCase();
while (["boy", "girl"].indexOf(gender) == -1) {
gender = prompt("Please only respond with boy or girl. Now, are you a boy or a girl?");
}
The proper condition would be
while (gender !== 'boy' && gender !== 'girl'){
That's because ("boy" || "girl") will always end up as "boy", therefore the while will look like while(gender !== 'boy'). The || in this case is called a "default" operator, a clever use of the logical OR . If the value on the left side is truthy, it will use the left side value. Otherwise, it will evaluate (hence "default") the right side.

Formatting text for output - Error: "Undefined is null or not an object" - Javascript

I am writing a program that will take the contents of a text area, pull out the important info, format it and then output it.
I have successfully made my program pass all the info into an array.
Currently I am working on getting the program to identify where the customer's name is located (it will always be between "Name" and either "Details" or "Customer" if "Details" is not in the correct location in the array.
// Parse the input box into an array
var inputArr = document.getElementById("inputBox").value.split(/[\s]/);
// Instantiate variables
var custDet, contactName, phone, companyName, email;
// Pull out all strings between "Name" and "Email" ("Card" should always be after "Email" or else it's the wrong string
if(inputArr[inputArr.indexOf("Email") + 1] == "Card") {
custDet = inputArr.slice(inputArr.indexOf("Name") + 1, inputArr.indexOf("Email"));
// Pass the customer's name into the string contactName
for(i = 0; custDet[i] != "Details" || custDet[i] != "Customer" || i < custDet.length; i++) {
if(custDet[i].search(",") != -1) {
var temp = custDet[i].split(/[,]/);
temp.reverse();
contactName = contactName + temp.join(" ");
}
}
contactName = contactName + custDet.join(" ");
} else {
contactName = prompt("Error: Could not locate a valid Contact Name. Please input Contact Name.");
phone = prompt("Error: Could not locate a valid Contact Phone Number. Please input Contact Phone Number.");
companyName = prompt("Error: Could not locate a valid Company Name. Please input Company Name.");
email = prompt("Error: Could not locate a valid Email Address. Please input Email Address.");
}
The error is being thrown on...
if(custDet[i].search(",") != -1) {
And I don't understand why. Any help with my logic would also be appreciated.
Thank you all. :)
That error likely means that you tried to reference item i of custDet, but custDet didn't have that many elements in it.
Your for loop is "non-standard":
for(i = 0; custDet[i] != "Details" || custDet[i] != "Customer" || i < custDet.length; i++)
and I suspect that's the source of the problem. i becomes higher than custDet.length, so that means custDet[i] returns undefined. Since undefined != "Details" is true, the loop keeps going past custDet.length.
You probably want &&, not ||. Otherwise, the condition is never not met and the loop won't end.
Simple explanation: For the first piece to be false, custDet[i] must equal "Details". But if that's the case then custDet[i] != "Customer" will be true, and the loop will continue. For all other values of custDet[i], custDet[i] != "Details" will be true and the loop will continue.

Categories

Resources