prompt how to loop to be sure to have the correct value ?

Recommended Posts


i would have a prompt box who check different state

  • length of the name
  • not the same name than the opponent

but how do you do to loop this function to be sure that the player don't press ok at the final dialog box and have a name_player == null  ? => see in the snippet


var f={}
var name_opponent=["roger","gilbert"]

	for (var i = 0; i < name_opponent.length; i++){
		return (st === name_opponent[i])

	let test = localStorage.getItem("username")
	if(typeof test != "string"){
		name_player = prompt("Please enter your name", "Anonymous")
		if(name_player) {
			if (name_player.length < 4) {
				name_player = prompt("Please enter min. 4 letters", "Anonymous")
			if(f.check_if_username_is_not_in_database_enemy(name_player) == true && name_player.length > 4){
				localStorage.setItem("username", name_player)
			if(f.check_if_username_is_not_in_database_enemy(name_player) == false){
				name_player = prompt("Name already exist, please choose a different name", "Anonymous")
//if the player press ok the name_player === null



Share this post

Link to post
Share on other sites

window.prompt() is convenient but may create some weird traps.  My tip would be to separate the UI from the logic.  Take a few steps back and define what the data validation function looks like, implement that first.  Then call the prompt (whether window.prompt or an alternative UI) "while" the validation function returns a falsy.  Then it'll neatly repeat until a valid name is supplied.  No recursion should be needed - ideally each function should do a single thing, and return as soon as that thing is done.

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.