0

this simple code works fine

   var gotname= false;

while (gotname==false){

var username =prompt ("passanger ,what's yout name");
 if (confirm("ar u " + username + "?")){
alert ("welcome "+ username);
gotname=true;
}

}

after add some validation conditions to ensure that the input not null and words only .the code didn't work as i want the massage alert confirm("ar u " + username + "?") didn't catch the username value and show instead value "false "

and this is my code

var gotname= false;

while (gotname==false){

var username =prompt ("passanger ,what's yout name");
  if( (username === null) || (username =! /^[A-Za-z ]+$/.test(username)) ){alert("enter valid one without numbers ! words only")}

else
 {confirm("ar u " + username + "?")}

alert ("welcome "+ username);
gotname=true;


}

and tried too

var gotname= false;

while (gotname==false){

var username =prompt ("passanger ,what's yout name");
if( username === null && username =! /^[A-Za-z ]+$/.test(username) ){alert("enter valid one")}


else if (confirm("ar u " + username + "?")){
alert ("welcome "+ username);
gotname=true;
}

}
1
  • The error is with (username =! /^[A-Za-z ]+$/.test(username)). The operator is !=, but that doesn't even seem right. Commented Oct 5, 2014 at 12:03

1 Answer 1

1

try this one:

<script type="text/javascript">
    function isUsernameValid(username) {
        return /^[A-Za-z ]+$/.test(username);
    }
var gotname= false;
while (gotname==false){
    var username = prompt ("passanger ,what's yout name");
    if( (username === null) || !isUsernameValid(username) ){
    alert("enter valid one without numbers ! words only")
} else {
    confirm("ar u " + username + "?")
    alert ("welcome "+ username);
}
gotname=true;


}
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

this works well, thanks .and what about if i want to show the massage "passenger ,what's yout name" again in case the user enter valid format (not words) because in this code if he write a bad format he will got a massage but after that it gone to end the loop because it becomes true and i need to end the loop after he did what i want he to did @Mandrake

Your Answer

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