javascript输入验证没有用

时间:2014-10-05 11:50:25

标签: javascript validation while-loop conditional

这个简单的代码工作正常

   var gotname= false;

while (gotname==false){

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

}

添加一些验证条件后,确保输入不为空,只有单词。代码不能正常工作 按摩警报确认(“ar u”+用户名+“?”) 没有捕获用户名值而是显示值“false”

这是我的代码

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;


}

也尝试了

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 个答案:

答案 0 :(得分:1)

试试这个:

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