1

If i want write an if statement where on the web page a prompt for your username pops up and i want it to be a string only how do i do this. For example if you type in a string it would say "username accepted" but if you type in a number it would say "username denied". The code I have so far says Username Accepted everytime.

let webUser = prompt("Please create a username", "typehere");

if (webUser != null) {
  document.getElementById("root").innerHTML =
    "Hello " + webUser + "! How are you today?";
}

if (typeof webUser == 'string' || webUser instanceof String) {
  alert('Username Accepted')
} else {
  alert('Username Denied')
}
1
  • Prompt always returns a string. It will never return a number or null. Commented Mar 28, 2018 at 6:10

3 Answers 3

1

If you want to implement without RegEx:

let webUser = prompt("Please create a username", "typehere");

if (webUser != null) {
	document.getElementById("root").innerHTML = "Hello " + webUser + "! How are you today?";
}

if (isNaN(+webUser)) {  
	alert('Username Accepted');
}
else {
	alert('Username Denied') ; 
}
<div id="root">

</div>

Sign up to request clarification or add additional context in comments.

Comments

0

The type of value you get from a prompt will always be a string, even if it has numbers in it. If you want to check to see if a string consists of only numbers, you can use a regular expression:

const webUser = prompt("Please create a username", "typehere");
if (/^\d+$/.test(webUser.trim())) console.log('invalid');
else console.log('valid');

Comments

0

prompt always returns a string data type. What you are trying to determine is whether that string is parseable as an integer. You can see some examples of how to do so here: how to parse string to int in javascript

1 Comment

Thanks I’ll check it out

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.