简体   繁体   中英

javascript input validation didn't work

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

}

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM