Jump to content

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


espace
 Share

Recommended Posts

hi,

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"]

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

f.prompt=()=>{
	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)
				alert(localStorage.getItem("username"))
			}
			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
			}
		}
	}
}

f.prompt()

 

Link to comment
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.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...