Validate that multiple Prompts have a value - javascript

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 !

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

How to make an if statement with conditions that include "and" in javascript

I am trying to make a password and confirmation password match, without them both being just left blank.
I would like to add in this part about the password fields not being able to be left blank, in the if statement, by saying the passwords have the same value, and these values are not blank.
The function worked fine when it was just the if statement, saying that the passwords had to match in order for the welcome alert to come up, and have found that the and symbol in javascript is && but i don't know how to use it in the context.
var check = function() {
if (document.getElementById('psw').value ==
document.getElementById('psw-repeat').value)
&&
(document.getElementById('psw').value) != ""
&&
(document.getElementById('psw-repeat').value) != "" }
else {
alert("passwords do not match")
}
}
I would expect this code to say that the passwords haven't been filled out, if they haven't, to say welcome if the password and confirmation password match, and to say the passwords do not match if they do not match.
I'm not sure what I've done wrong but would love if anyone could help.
:))
You're not closing the whole if statement with ()
Okay, best way to do conditions it like following.
why best
optimized, you don't need to get values from dom again and again for
condition checking
easy to read if condition.
If code is not readable then not the best code
So always try to break the conditions
function() {
var password = document.getElementById('psw').value;
var password_repeat = document.getElementById('psw-repeat').value;
if (password == password_repeat && password != "" && password_repeat != "")
{
// code ..........
}
else
{
alert("passwords do not match")
}
}
For better code checking and styling, use some IDEs like VSCode Atom Bracket
but personally I like the VSCode
The only real problem is out-of-place parentheses and curly braces, but this way adds a couple of improvements beyond those simple fixes.
// Select HTML elements
const psw = document.getElementById("psw");
const pswRepeat = document.getElementById("psw-repeat");
const checkBtn = document.getElementById("checkBtn");
// Listen for button clicks
checkBtn.addEventListener("click", check);
// Validate passwords
function check(){
if(pswRepeat.value === psw.value && psw.value != ""){
// We know they are the same, and psw is not empty (so neither is pswRepeat)
alert("good");
}
else{
alert("passwords do not match");
}
}
<input id="psw" />
<input id="psw-repeat" />
<button id="checkBtn">Check</button>
You forgot to close the parenthesis.
You need better indentation to detect these kinds of problems early and some separation of logic to keep the code readable.Something like this :
var check = function() {
if (isValid()) {
//Welcome here
} else {
alert("passwords do not match")
}
}
function isValid() {
var psw = document.getElementById('psw').value;
var repeatPsw = document.getElementById('psw-repeat').value;
//Logic to check for password
if (psw == repeatPsw &&
psw != "" &&
repeatPsw != ""
)
return true;
return false;
}

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

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!

How to test the null value condition in Javascript?

Below is the code,
<p id="sayHello"></p>
<script type="text/javascript">
var yourName = window['prompt']("What is your name?");
if (yourName != null) {
window['document']['getElementById']("sayHello").innerHTML = "Hello " + yourName;
} else {
window['alert']("Please enter your name next time");
}
</script>
for which, else block need to get executed based on the input given in prompt.
What should be the input in prompt box to test null value of primitive type Null?
When you click cancel on the prompt box the else block will get executed.
Per the MDN window.prompt docs:
If the user clicks OK without entering any text, an empty string is returned.
So really you want to check if (yourName !== null && yourName !== "") since the prompt is really returning the empty string (thus causing your else clause to be executed incorrectly since it's passing the not null check).
I think you actualy looking for empty string.Also null is a primitive value & null represent an "empty" value, that is no object value is present.
So to check null we can use
if(somVar === null && typeof somVar ==='object')
So you can arrange you code as
var yourName = window['prompt']("What is your name?");
if (yourName === null & typeof(yourName) ==='object') {
alert("Please enter your name next time");
} else {
document.getElementById("sayHello").innerHTML = "Hello " + yourName;
}
Also note this will ONLY test for null and will not pass for "",undefined,false,0 & NaN.
Beside is there any reason to use
window['document']['getElementById']("sayHello")
when it can be done like this
document.getElementById("sayHello").innerHTML
If you are checking for empty string , then you also have to validate that input is not empty
DEMO

onclick event on submit button

I'm trying to make a verification that an input text has an email format after clicking submit buttom and calling a js function. The first problem i encounter is that after some tests, i've seen that it doesnt enter the called function. After this, i think everything should be ok, but just in case in order to not post 2 almost equal questions within minutes, ill include the most important part.
Summarizing, it should check:
-The email field is not null
-The email field has an # (without taking into account order etc)
Then it should tell if it found any problem, if not leave everything unchanged
I hope i made my point, if not i can try to explain it again..
<input type="text" name="email" id="email">
<input type="submit" onclick=" proceed()"/>
<script>
proceed(){
var email= document.getElementById('email').value;
var problems;
if (email == ""){
problems = "Empty variable \n";
}
var noat = true;
for (int i=0; email.length; i++){
if (email.charAt(i) == "#"){ //Compare each character
noat=false;
break;
}
}
if (email=="" || noat=true){
problems += "No # \n"
alert(problems);
}
}
</script>
<form onsubmit="return proceed();">
<input type="text" name="email" id="email">
<input type="submit" />
</form>
<script>
function proceed() {
var email = document.getElementById('email').value;
var problems = "";
if (email == "") {
problems = "Empty variable \n";
}
var noat = false;
if (email.indexOf("#") == -1) noat = true;
// for (int i=0; i< email.length; i++){
// if (email.charAt(i) == "#"){ //Compare each character
// noat=false;
// break;
//}
if (email == "" || noat == true) {
problems += "No # \n";
alert(problems);
}
if (problems == "")
return true;
else
return false;
}
</script>
Instead of using onclick, i think you should use onsubmit and instead of comparing each character for # symbol, you should use email test regular expressions.
there are plenty of those online, just google.
sample regular expressions
Well I was about to write this myself but I happened to have found it like 4 hours ago. This will help you.
<script>
function proceed()
{
var email = document.getElementById("email").value;
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos+2 || dotpos+2 >= email.length)
{
alert("Not a valid e-mail address");
return false;
}
};
</script>
<form onsubmit="proceed();">
<input type="text" name="email" id="email" />
<input type="submit" />
</form>
Your code had a lot of typos, just take your time when writing. This is from w3schools
This question has already been marked as answered, but I feel that there a few key takeaways / learning points from the question, so i've added my input below, fwiw.
Right now the code in your question starts off with proceed() { ... }. You should change this to function proceed() { ... } to make it a proper function declaration
It's a good habit to define your variables at the top of your scope in which they are being used. As of now you have the email and problems vars declared next to each other, and that's good. However, var noat is all by itself a few lines down. Moving it up to the other declarations helps the reader of your code understand which variables are to be used in this function
On the fourth line of your function you check to see if email is an empty string. If it is, you set the problems variable. But if it's empty, we can stop where we are. You can just return problems; and be done with the function.
It's already been pointed out, but email.indexOf("#") uses the native JS method to do what you're doing in the string iterator.
for(int i=0; ...) I thought the int i =0 looked funny, so I tried typing it into the javascript console on my browser. I got an error. You can change this to for(var i = 0; ...) for the correct syntax.
Later on in the function we ask if email is empty again: if(email == ""). But we've already asked this question, and would have exited the function if it was true. We can't have an # symbol in the string if the string is empty.
This has been mentioned before but you probably want to use a regular expression to check the email.
Next we have noat = true. This will actually always evaluate to true because the result of the assignment is truthy. You're setting the value of noat to true, and javascript is like "Cool awesome looks good to me". It doesn't check if noat was originally set to true or false.
I've created and tested a jsfiddle that follows most of these recommendations. It also shows a way to make the code more concise and achieve a similar goal. Sorry if this comes off as too preachy/know-it-all, I definitely don't. This question piqued my interest and I had to respond!
window.proceed = function () {
var email = document.getElementById('email').value;
if (email == "") {
alert("Empty variable \n");
} else if (email.indexOf("#") == -1) {
alert("No # \n");
} else return true;
}
jsfiddle

Categories

Resources