gpt4 book ai didi

javascript - 输入验证 JavaScript?

转载 作者:行者123 更新时间:2023-11-28 17:05:58 26 4
gpt4 key购买 nike

我需要向用户询问提示,但他们只能输入某些单词才能接受答案,如果用户没有用正确的单词回答,则会说它无效并再次询问问题。< br/> 这必须仅使用 JavaScript 来完成。

var entering = confirm('Confirm to add state or territory');
if (!entering) {
return;
} else {
while (true) {
stInput = prompt('Enter state or territory');

function validateUserChoice(stInput) {
if (stInput !== "Queensland" && stInput !== "New South Wales" && stInput !== "Victoria" && stInput !== "Tasmania" && stInput !== "Northern Territory" && stInput !== "Western Australia" && stInput !== "South Australia" && stInput !== "Australian Capital Territory") {
alert("invalid state or territory");
} else {
return false;
}
}
populationInput = parseInt(prompt('Enter population for ' + stInput + ''));

while (isNaN(populationInput)) {
alert('Your input was invalid');
populationInput = parseInt(prompt('Enter population for ' + stInput + ''));
}
changeInput = parseFloat(prompt('Enter growth rate for ' + populationInput + ''));

while (isNaN(changeInput)) {
alert('Your input was invalid');
changeInput = parseFloat(prompt('Enter growth rate for ' + populationInput + ''));
}

break;
}

}

这是我到目前为止所做的,但它没有验证,所以我做错了一些事情,只是不确定是什么。

用户只能回答的词有:昆士兰新南威尔士维多利亚塔斯马尼亚北领地西澳大利亚南澳大利亚澳大利亚首都领地

最佳答案

当您编写function validateUserChoice(stInput)时,您是在声明一个函数,而不是调用它。因此,您应该声明您的函数并将其调用为 validateUserChoice(stInput) 还是根本不使用函数。

按照一段代码,我相信您打算这样做:

    var entering = confirm('Confirm to add state or territory');
if (!entering) {
return;
} else {
stInput = prompt('Enter state or territory');
while (stInput !== "Queensland" && stInput !== "New South Wales" && stInput !== "Victoria" && stInput !== "Tasmania" && stInput !== "Northern Territory" && stInput !== "Western Australia" && stInput !== "South Australia" && stInput !== "Australian Capital Territory") {
//stay in loop while stInput is not equal any of the strings
alert("invalid state or territory");
stInput = prompt('Enter state or territory');
}
populationInput = parseInt(prompt('Enter population for ' + stInput + ''));

while(isNaN(populationInput)) {
alert('Your input was invalid');
populationInput = parseInt(prompt('Enter population for ' + stInput + ''));
}
changeInput = parseFloat(prompt('Enter growth rate for ' + populationInput + ''));

while(isNaN(changeInput)) {
alert('Your input was invalid');
changeInput = parseFloat(prompt('Enter growth rate for ' + populationInput + ''));
}
}

关于javascript - 输入验证 JavaScript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55867427/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com